异步任务正在等待另一个任务

时间:2018-12-28 01:44:54

标签: c# asynchronous .net-core async-await

我有类似的代码:

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();
}

在ProcessAll中,我希望先执行firstBatchProcess,然后再执行SecondBatchProcess。因为我有来自FirstBatchPRocess的一些数据,以后将在SecondBatchProcess中使用。如果我运行此代码,由于SecondBatchProcess需要从FirstBatchProcess生成的数据,两者都将异步执行并导致错误。

注意:两个BatchProcesses都包含多个异步循环,因此我使用Task.WhenAll() 如何等待FirstBatchProcess完成然后执行SecondBatchProcess?

2 个答案:

答案 0 :(得分:3)

更新

  

所以当我调用Task.Wait()时,它将等待此任务完成   它将继续另一个过程吗?

自从您编辑了问题之后,如果我理解正确(我在两行之间阅读)

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

答案是肯定的,所有在FirstBatchProcess中启动的任务都将在执行SecondBatchProcess之前完成

原始

Task.WhenAll Method

  

创建一个任务,当所有提供的任务都完成时,该任务将完成   完成

我认为您可能会对await运算符

感到困惑

await (C# Reference)

  

将await运算符以异步方法应用于任务,以   在方法的执行中插入一个暂停点,直到   等待的任务完成。该任务代表正在进行的工作。

它实际上正在等待!

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");
}

输出

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

所有任务都已完成。

答案 1 :(得分:0)

如何使用Task.Factory.StartNew();

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

如果DoAsyncThing()使用UI进行操作,则应将TaskScheduler.FromCurrentSynchronizationContext()StartNew()一起使用

希望对您有帮助。

谢谢。

相关问题