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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With