Search code examples
foreachtask-parallel-libraryaggregateexception

Cannot use "foreach" to go through exceptions because Exception does not contain 'GetEnumerator'


I want to report about Exceptions that are thrown during execution of some tasks:

//waiting for all the tasks to complete
try
{
    Task.WaitAll(task1, task2, task3);
}
catch (AggregateException ex)
{
    //enumerate the exceptions
    foreach (Exception inner in ex.InnerException)
    {
        Console.WriteLine("Exception type {0} from {1}", inner.GetType(), inner.Source);
    }
}

However, I cannot use foreach loop in that case.

Is there any workaround that issue?


Solution

  • InnerException isn't a collection or Exceptions so you can't enumerate over it, you should use InnerExceptions. This article shows how to correctly handle the exceptions: https://msdn.microsoft.com/en-us/library/dd537614(v=vs.110).aspx