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

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

    I know this is a question that's already answered but the chosen answer doesn't really solve the OP's problem, so I thought I would post this.

    This solution gives you the aggregate exception (i.e. all the exceptions that were thrown by the various tasks) and doesn't block (workflow is still asynchronous).

    async Task Main()
    {
        var task = Task.WhenAll(A(), B());
    
        try
        {
            var results = await task;
            Console.WriteLine(results);
        }
        catch (Exception)
        {
            if (task.Exception != null)
            {
                throw task.Exception;
            }
        }
    }
    
    public async Task A()
    {
        await Task.Delay(100);
        throw new Exception("A");
    }
    
    public async Task B()
    {
        await Task.Delay(100);
        throw new Exception("B");
    }
    

    The key is to save a reference to the aggregate task before you await it, then you can access its Exception property which holds your AggregateException (even if only one task threw an exception).

    Hope this is still useful. I know I had this problem today.

提交回复
热议问题