Why doesn't await on Task.WhenAll throw an AggregateException?

前端 未结 8 1768
我在风中等你
我在风中等你 2020-12-04 15:14

In this code:

private async void button1_Click(object sender, EventArgs e) {
    try {
        await Task.WhenAll(DoLongThingAsyncEx1(), DoLongThingAsyncEx2(         


        
8条回答
  •  被撕碎了的回忆
    2020-12-04 15:32

    In your code, the first exception is returned by design as explained at http://blogs.msdn.com/b/pfxteam/archive/2011/09/28/task-exception-handling-in-net-4-5.aspx

    As for your question, you will get the AggreateException if you write code like this:

    try {
        var result = Task.WhenAll(DoLongThingAsyncEx1(), DoLongThingAsyncEx2()).Result; 
    }
    catch (Exception ex) {
        // Expect AggregateException here
    } 
    

提交回复
热议问题