How Asynchronous Concurrency exceptions are handled

With Task.WhenAll, it allows Async Tasks to run simultaneously but how do we handle each task’s exception.

We will try catch it like normally do with synchronous programming. When each task throw exception it is stored in the AggregateException object which has an InnerExceptions, a ReadOnlyCollection<Exception> that contains the list of exceptions that each task thrown.

We can try catch and loop through its InnerExceptions collection to get each of Task’s exception:

Task t1 = Task.Run(() => throw new InvalidOperationException("Task 1 failed"));
Task t2 = Task.Run(() => throw new ArgumentException("Task 2 failed"));

Task allTasks = Task.WhenAll(t1, t2);

try
{
await allTasks; // await all tasks
}
catch
{
// Inspect all exceptions from allTasks
if (allTasks.Exception != null)
{
foreach (var ex in allTasks.Exception.InnerExceptions)
{
Console.WriteLine(ex.Message);
}
}
}

Info: allTasks.Exception is an object of AggregateException Type.

Output:

Leave a Reply

Your email address will not be published. Required fields are marked *