为什么不等待Task.WhenAll抛出一个AggregateException? [英] Why doesn't await on Task.WhenAll throw an AggregateException?

查看:134
本文介绍了为什么不等待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 ,因为至少有一个任务正在等待抛出异常。相反,我正在收回一个任务抛出的一个异常。

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

推荐答案

我不完全记住在哪里,但我读到某个地方,新的 async / 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块中,你会得到实际的异常不是聚合的。这有助于我们编写更自然和直观的代码。

So, in catch block, you get the actual exception and not the aggregated one. This helps us write more natural and intuitive code.

这也是为了更容易地将现有代码转换为使用 async / await 而需要的,

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.

- 修改 -

获得:


Bill Wagner说:(在发生异常时)

...当您使用等待时,编译器生成的代码将
AggregateException并抛出底层异常。通过利用
等待,您可以避免额外的工作来处理由
Task类中定义的Task.Result,Task.Wait和其他Wait方法使用的AggregateException类型
。这是使用等待而不是基于
的任务方法的另一个原因....

...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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆