I have some code I'm going to parallelize. It currently looks something like this:
foreach (var item in collection)
{
if (error)
{
throw new Exception();
}
}
The exception and its stack trace are saved in a log file.
After parallelization, it would look like this:
Parallel.ForEach(collection, item =>
{
if (error)
{
throw new Exception();
}
});
When an exception is thrown, execution of the items that have not yet been scheduled will be cancelled. Items that are already scheduled, however, will not and cannot be cancelled. (Remember, this happens in parallel, which is why you use Parallel
in the first place.) They will run to the end, and may themselves throw exceptions.
Because of this, there might be multiple exceptions thrown in a parallel loop. That is why they are always wrapped in an AggregateException
, even when an exception was thown only once. You can catch that AggregateException
and enumerate through its InnerExceptions
property, which contains all exceptions thrown, together with their stack traces:
try
{
Parallel.ForEach(collection, item =>
{
if (error)
{
throw new Exception();
}
});
}
catch (AggregateException ex)
{
foreach (var exception in ex.InnerExceptions)
{
// do something
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments