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

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<int> A()
{
    await Task.Delay(100);
    throw new Exception("A");
}

public async Task<int> 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.

Leave a Comment