gpt4 book ai didi

c# - 等待另一个任务的异步任务

转载 作者:太空宇宙 更新时间:2023-11-03 22:37:58 25 4
gpt4 key购买 nike

我有这样的代码:

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 ?

最佳答案

更新

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

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

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

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

原创

Task.WhenAll Method

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

我认为您可能对 await 运算符感到困惑

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.

它实际上在等待!

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

所有任务都已完成。

关于c# - 等待另一个任务的异步任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53952791/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com