当谈到 .NET 中的 async/await 时,我有点困惑...
考虑以下方法:
public async Task DoSomething() {
IEnumerable<Task> ts = GetSomeTasks(); // Some tasks that would do some random IO stuff, or whatever
await Task.WhenAll(ts);
Console.WriteLine("All tasks completed!");
}
Console.WriteLine
的调用是否保证在等待ts
中的任务后执行?我想我已经看到在访问任务结果之前 await 似乎不会像那样“阻塞”的情况。适用什么规则?
最佳答案
Is the call to Console.WriteLine guaranteed to be executed after the tasks in ts have been awaited?
是的。
I think I've seen cases where await doesn't seem to "block" like that until the task result is accessed.
不,不是这样的。您只会在 await 运算符之后到达语句(或者可能是语句中 within 的下一个表达式,例如 for (await a) + (await b)
once the thing正在等待的已经完成。
请注意 Task.WhenAll
本身不是阻塞方法(与 Task.WaitAll
不同)- 但它会返回一个任务,该任务在所有任务都通过之前不会完成因为参数已经完成。
关于c# - 在 C# .NET block 中等待 Task.WhenAll 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60966013/