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

前端 未结 8 1773
我在风中等你
我在风中等你 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:49

    You can traverse all tasks to see if more than one have thrown an exception:

    private async Task Example()
    {
        var tasks = new [] { DoLongThingAsyncEx1(), DoLongThingAsyncEx2() };
    
        try 
        {
            await Task.WhenAll(tasks);
        }
        catch (Exception ex) 
        {
            var exceptions = tasks.Where(t => t.Exception != null)
                                  .Select(t => t.Exception);
        }
    }
    
    private Task DoLongThingAsyncEx1()
    {
        return Task.Run(() => { throw new InvalidTimeZoneException(); });
    }
    
    private Task DoLongThingAsyncEx2()
    {
        return Task.Run(() => { throw new InvalidOperationException(); });
    }
    

提交回复
热议问题