简体   繁体   中英

Async task waiting for another task

I have code like :

private async Task<bool> DoAsyncThing()
{
  await doOtherThings();
} 

private async Task<bool> DoAsyncThing2()
{
  await doOtherThings2();
} 

private async Task<bool> SaveAll()
{
   return await _context.SaveChangesAsync() > 0;
}

public async Task<bool> FirstBatchProcess()
{
    var tasks = new List<Task<bool>>();
    ...
    users.Foreach(user => {
        task.Add(this.DoAsyncThing());
    });
    await Task.WhenAll(tasks);
    return await this.SaveAll();
}

public async Task<bool> SecondBatchProcess()
{
    // get all data from batch 1 and then do calculation
    var tasks = new List<Task<bool>>();
    ...
    users.Foreach(user => {
        task.Add(this.DoAsyncThing2());
    });
    await Task.WhenAll(tasks);
    return await this.SaveAll();
}


public async Task<bool> ProcessAll()
{
    await this.FirstBatchProcess();
    await this.SecondBatchProcess();
}

In the ProcessAll I want firstBatchProcess to be done first before doing SecondBatchProcess. Because I have some data from FirstBatchPRocess to be used later in SecondBatchProcess. If I run this code, both will be executed async and caused error because the SecondBatchProcess required the data generated from FirstBatchProcess.

note: both BatchProcesses contains multiple async loop so I use Task.WhenAll() How to wait FirstBatchProcess finished then executed SecondBatchProcess ?

Update

so when I call Task.Wait() it will waiting this task to be done then it will continue another process ?

Since you edited your question, and if i understand you correctly (i'm reading between the lines)

await this.FirstBatchProcess();  // will wait for this to finish
await this.SecondBatchProcess(); // will wait for this to finish

The answer is yes all tasks started in FirstBatchProcess will complete before it executes SecondBatchProcess

Original

Task.WhenAll Method

Creates a task that will complete when all of the supplied tasks have completed .

I think you maybe getting confused with the await operator

await (C# Reference)

The await operator is applied to a task in an asynchronous method to insert a suspension point in the execution of the method until the awaited task completes . The task represents ongoing work.

It actually waits!

Your Full Demo Here

private static async Task DoAsyncThing()
{
    Console.WriteLine("waiting");
    await Task.Delay(1000);
    Console.WriteLine("waited");
}

private static async Task SaveAll()
{
    Console.WriteLine("Saving");
    await Task.Delay(1000);
}

public static async Task ProcessAll()
{
    var tasks = new List<Task>();
    for (int i = 0; i < 10; i++)
    {
        tasks.Add(DoAsyncThing());
    }

    await Task.WhenAll(tasks);
    await SaveAll();
    Console.WriteLine("Saved");
}

public static void Main()
{
    ProcessAll().Wait();
    Console.WriteLine("sdf");
}

Output

waiting
waiting
waiting
waiting
waiting
waiting
waiting
waiting
waiting
waiting
waited
waited
waited
waited
waited
waited
waited
waited
waited
waited
Saving
Saved
sdf

All tasks were completed.

How about using Task.Factory.StartNew();

Task.Factory.StartNew(() =>
{
     return DoAsyncThing();
}).ContinueWith(x =>
{
     if (x.Result)
        SaveAll();
});

if DoAsyncThing() do something with UI, you should use TaskScheduler.FromCurrentSynchronizationContext() with StartNew()

I hope it helps.

Thank you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM