Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Task.WhenAll wait for all the tasks in case of exceptions

I have two tasks. I run both of them with Task.WhenAll. What happens if one of them throws an exception? Would the other one complete?

like image 632
Jonatan Dragon Avatar asked Mar 21 '18 10:03

Jonatan Dragon


People also ask

Does task WhenAll throw exception?

WhenAll(tasklist)", it will throw an exception if any of the tasks are faulted. Since we have 2 faulted tasks here, that's exactly what happens.

How does task WhenAll work?

Task. WhenAll creates a task that will complete when all of the supplied tasks have been completed. It's pretty straightforward what this method does, it simply receives a list of Tasks and returns a Task when all of the received Tasks completes.

How do you handle exceptions in tasks?

Exceptions are propagated when you use one of the static or instance Task. Wait methods, and you handle them by enclosing the call in a try / catch statement. If a task is the parent of attached child tasks, or if you are waiting on multiple tasks, multiple exceptions could be thrown.

What is the difference between task WaitAll and task WhenAll?

The Task. WaitAll blocks the current thread until all other tasks have completed execution. The Task. WhenAll method is used to create a task that will complete if and only if all the other tasks have completed.


1 Answers

Just run this code to test it:

private static async Task TestTaskWhenAll()
{
    try
    {
        await Task.WhenAll(
            ShortOperationAsync(),
            LongOperationAsync()
        );
    }
    catch (Exception exception)
    {
        Console.WriteLine(exception.Message); // Short operation exception
        Debugger.Break();
    }
}

private static async Task ShortOperationAsync()
{
    await Task.Delay(1000);
    throw new InvalidTimeZoneException("Short operation exception");

}

private static async Task LongOperationAsync()
{
    await Task.Delay(5000);
    throw new ArgumentException("Long operation exception");
}

Debugger will stop in 5 seconds. Both exceptions are thrown, but Debugger.Break() is hit only once. What is more, the exception value is not AggregateException, but InvalidTimeZoneException. This is because of new async/await which does the unwrapping into the actual exception. You can read more here. If you want to read other Exceptions (not only the first one), you would have to read them from the Task returned from WhenAll method call.

like image 185
Jonatan Dragon Avatar answered Sep 18 '22 13:09

Jonatan Dragon