问题描述
在此code:
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
,因为它正在等待的任务,至少有一个引发了异常。相反,我得到回来的任务之一抛出一个例外。
I expected WhenAll
to create and throw an AggregateException
, since at least one of the tasks it was awaiting on threw an exception. Instead, I'm getting back a single exception thrown by one of the tasks.
确实 WhenAll
并不总是创建一个 AggregateException
?
Does WhenAll
not always create an AggregateException
?
推荐答案
我完全不记得在哪里,但我读的地方,新的异步/的await 的关键字,他们解开了 AggregateException
进入实际例外。
I don't exactly remember where, but I read somewhere that with new async/await keywords, they unwrap the AggregateException
into the actual exception.
所以,在catch块,你得到的实际例外,而不是聚合之一。这可以帮助我们写出更自然和直观code。
So, in catch block, you get the actual exception and not the aggregated one. This helps us write more natural and intuitive code.
这也需要对现有code更容易转化为使用的异步/的await 的,其中有很多code的预计具体的例外规定,而不是聚集例外。
This was also needed for easier conversion of existing code into using async/await where the a lot of code expects specific exceptions and not aggregated exceptions.
- 编辑 -
明白了:
比尔·瓦格纳说:(在当例外情况的)
...当你使用等待,由编译器生成的code解开了
AggregateException并引发潜在的异常。通过利用
的await,避免额外的工作来处理AggregateException类型
在由Task.Result,Task.Wait,和其他等待使用方法定义
Task类。这是另一个理由使用等待,而不是
基本任务的方法....
...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....
这篇关于为什么不扔Task.WhenAll AggregateException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!