Async CTP Task.WaitAll()
和Task.WhenAll()
Async CTP有什么区别?您能否提供一些示例代码来说明不同的用例?
Async CTP Task.WaitAll()
和Task.WhenAll()
Async CTP有什么区别?您能否提供一些示例代码来说明不同的用例?
Answers:
Task.WaitAll
阻塞当前线程,直到一切完成。
Task.WhenAll
返回一个任务,表示等待一切完成的动作。
这意味着从异步方法中,您可以使用:
await Task.WhenAll(tasks);
...这意味着您的方法将在完成所有操作后继续,但是您不会在此之前一直绑一个线程。
WhenAll
,但这与阻止线程不同。
尽管JonSkeet的回答以一种典型的出色方式解释了这种差异,但还有另一个差异:异常处理。
Task.WaitAll
AggregateException
当任何任务抛出时,您将抛出一个,您可以检查所有抛出的异常。将await
在await Task.WhenAll
解包AggregateException
和“返回”只有第一个例外。
当下面的程序执行时await Task.WhenAll(taskArray)
,输出如下。
19/11/2016 12:18:37 AM: Task 1 started
19/11/2016 12:18:37 AM: Task 3 started
19/11/2016 12:18:37 AM: Task 2 started
Caught Exception in Main at 19/11/2016 12:18:40 AM: Task 1 throwing at 19/11/2016 12:18:38 AM
Done.
执行以下程序时Task.WaitAll(taskArray)
,输出如下。
19/11/2016 12:19:29 AM: Task 1 started
19/11/2016 12:19:29 AM: Task 2 started
19/11/2016 12:19:29 AM: Task 3 started
Caught AggregateException in Main at 19/11/2016 12:19:32 AM: Task 1 throwing at 19/11/2016 12:19:30 AM
Caught AggregateException in Main at 19/11/2016 12:19:32 AM: Task 2 throwing at 19/11/2016 12:19:31 AM
Caught AggregateException in Main at 19/11/2016 12:19:32 AM: Task 3 throwing at 19/11/2016 12:19:32 AM
Done.
该程序:
class MyAmazingProgram
{
public class CustomException : Exception
{
public CustomException(String message) : base(message)
{ }
}
static void WaitAndThrow(int id, int waitInMs)
{
Console.WriteLine($"{DateTime.UtcNow}: Task {id} started");
Thread.Sleep(waitInMs);
throw new CustomException($"Task {id} throwing at {DateTime.UtcNow}");
}
static void Main(string[] args)
{
Task.Run(async () =>
{
await MyAmazingMethodAsync();
}).Wait();
}
static async Task MyAmazingMethodAsync()
{
try
{
Task[] taskArray = { Task.Factory.StartNew(() => WaitAndThrow(1, 1000)),
Task.Factory.StartNew(() => WaitAndThrow(2, 2000)),
Task.Factory.StartNew(() => WaitAndThrow(3, 3000)) };
Task.WaitAll(taskArray);
//await Task.WhenAll(taskArray);
Console.WriteLine("This isn't going to happen");
}
catch (AggregateException ex)
{
foreach (var inner in ex.InnerExceptions)
{
Console.WriteLine($"Caught AggregateException in Main at {DateTime.UtcNow}: " + inner.Message);
}
}
catch (Exception ex)
{
Console.WriteLine($"Caught Exception in Main at {DateTime.UtcNow}: " + ex.Message);
}
Console.WriteLine("Done.");
Console.ReadLine();
}
}
await t1; await t2; await t3;
vsawait Task.WhenAll(t1,t2,t3);