Not logged in - Login

AggregateException Usage with WhenAll

If exceptions occur when calling Task.WhenAll(), all of the exceptions may not be captured with the standard Exception try-catch processing block. The following illustrates usage of the AggregateException property inside of the Task object.

// start some async tasks
var tsk1 = Test1Async();
var tsk2 = Test2Async();
var tsk3 = Test3Async();

// get a task that will be awated to catch any exceptions
var allTasks = Task.WhenAll(tsk1, tsk2, tsk3);
try
{
   // await the WhenAll() task
   await allTasks;
}
catch (Exception ex)
{
   // catch the aggregate exception
   if (allTasks.Exception != null)
   {
      // handle the AggregateException
      // get a reference to the Aggregate Exception
      AggregateException aggrEx = allTasks.Exception;

      // get collection of exceptions live in the InnerExceptions property
      ReadOnlyCollection<Exception> exceptions = aggrEx.InnerExceptions;
   }
}