繁体   English   中英

异步任务等待另一个任务

[英]Async task waiting for another task

我的代码如下:

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中,我想在执行SecondBatchProcess之前先完成firstBatchProcess。 因为我有来自FirstBatchPRocess的一些数据,以便稍后在SecondBatchProcess中使用。 如果我运行此代码,两者都将执行异步并导致错误,因为SecondBatchProcess需要从FirstBatchProcess生成的数据。

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

更新

所以当我调用Task.Wait()时,它会等待这个任务完成然后它会继续另一个进程吗?

既然你编辑了你的问题,如果我理解正确(我正在读行)

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

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

原版的

Task.WhenAll方法

创建将在所有提供的任务完成后完成的任务

我想你可能await运算符感到困惑

等待(C#参考)

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

它实际上等待!

你在这里完整的演示

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

所有任务都已完成。

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

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

如果DoAsyncThing()对UI执行某些操作,则应将TaskScheduler.FromCurrentSynchronizationContext()StartNew()

我希望它有所帮助。

谢谢。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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