.net – 为什么不等待Task.WhenAll抛出一个AggregateException?

在这段代码中:

private async void button1_Click(object sender, EventArgs e) {
    try {
        await Task.WhenAll(DoLongThingAsyncEx1(), DoLongThingAsyncEx2());
    }
    catch (Exception ex) {
        // Expect AggregateException, but got InvalidTimeZoneException
    }
}

Task DoLongThingAsyncEx1() {
    return Task.Run(() => { throw new InvalidTimeZoneException(); });
}

Task DoLongThingAsyncEx2() {
    return Task.Run(() => { throw new InvalidOperation();});
}

我期望WhenAll创建和抛出一个AggregateException,因为至少有一个任务,它正在等待抛出一个异常。相反,我收回一个任务抛出的单个异常。

WhenAll不总是创建一个AggregateException?

我不记得在哪里,但我读到某个地方,使用新的async / await关键字,他们解开AggregateException到实际的异常。

所以,在catch块,你得到实际的异常,而不是聚合的。这有助于我们编写更自然和直观的代码。

这也需要更容易将现有代码转换为使用async / await,其中很多代码期望特定的异常,而不是聚合的异常。

– 编辑 –

得到它了:

An Async Primer by Bill Wagner

Bill Wagner said: (in When Exceptions Happen)

…When you use await, the code generated by the compiler unwraps the
AggregateException and throws the underlying exception. By leveraging
await, you avoid the extra work to handle the AggregateException type
used by Task.Result, Task.Wait, and other Wait methods defined in the
Task class. That’s another reason to use await instead of the
underlying Task methods….

http://stackoverflow.com/questions/12007781/why-doesnt-await-on-task-whenall-throw-an-aggregateexception

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:.net – 为什么不等待Task.WhenAll抛出一个AggregateException?