I have seen an example of AggregateException on the web and I\'m trying to figure out how it works. I have written a simple example, but my code for some reason
AggregateException is often used for catching exceptions, that might occur when waiting for a Task to complete. Because Task in general can consist of multiple others, we do not know, whether there will be one or more exceptions thrown.
Check the following example:
// set up your task
Action job = (int i) =>
{
if (i % 100 == 0)
throw new TimeoutException("i = " + i);
};
// we want many tasks to run in paralell
var tasks = new Task[1000];
for (var i = 0; i < 1000; i++)
{
// assign to other variable,
// or it will use the same number for every task
var j = i;
// run your task
var task = Task.Run(() => job(j));
// save it
tasks[i] = task;
}
try
{
// wait for all the tasks to finish in a blocking manner
Task.WaitAll(tasks);
}
catch (AggregateException e)
{
// catch whatever was thrown
foreach (Exception ex in e.InnerExceptions)
Console.WriteLine(ex.Message);
}