任务等待与 Task.WaitAll
Task await vs Task.WaitAll
就并行性而言,这些是等价的吗?
async Task TestMethod1()
{
Task<int> t1 = GetInt1();
Task<int> t2 = GetInt2();
await Task.WhenAll(t1, t2);
}
async Task TestMethod2()
{
Task<int> t1 = GetInt1();
await GetInt2();
await t1;
}
在TestMethod2
中,我主要是想了解GetInt1()
在等待GetInt2()
时是否开始执行。
是的,就"parallelism"(实际上并发)而言,它们几乎相同。
特别是,TAP docs 声明 returned 任务是 "hot",即:
All tasks that are returned from TAP methods must be activated... Consumers of a TAP method may safely assume that the returned task is active
因此,您的代码通过调用它们的方法启动 异步操作。他们 return 的任务已经在进行中。在这两个示例中,两个任务都是 运行 同时进行的。
使用两个 await
还是一个 await Task.WhenAll
并不重要。我更喜欢 Task.WhenAll
方法,因为 IMO 它更清楚地传达了并发的意图。此外,它只中断源上下文(例如 UI 线程)一次而不是两次,但这只是一个小问题。
就并行性而言,这些是等价的吗?
async Task TestMethod1()
{
Task<int> t1 = GetInt1();
Task<int> t2 = GetInt2();
await Task.WhenAll(t1, t2);
}
async Task TestMethod2()
{
Task<int> t1 = GetInt1();
await GetInt2();
await t1;
}
在TestMethod2
中,我主要是想了解GetInt1()
在等待GetInt2()
时是否开始执行。
是的,就"parallelism"(实际上并发)而言,它们几乎相同。
特别是,TAP docs 声明 returned 任务是 "hot",即:
All tasks that are returned from TAP methods must be activated... Consumers of a TAP method may safely assume that the returned task is active
因此,您的代码通过调用它们的方法启动 异步操作。他们 return 的任务已经在进行中。在这两个示例中,两个任务都是 运行 同时进行的。
使用两个 await
还是一个 await Task.WhenAll
并不重要。我更喜欢 Task.WhenAll
方法,因为 IMO 它更清楚地传达了并发的意图。此外,它只中断源上下文(例如 UI 线程)一次而不是两次,但这只是一个小问题。