CSharp Parallel Programming

Last Updated: 3/10/2022

Handle Exceptions in Parallel Loops

  • Any unhandled exception causes the loop to terminate as soon as all currently running iterations finish.
  • Add your own exception-handling logic to parallel loops,
  • Handle the case in which similar exceptions might be thrown on multiple threads concurrently,
  • Handle the case in which an exception thrown on one thread causes another exception to be thrown on another thread.
  • You can handle both cases by wrapping all exceptions from the loop in a System.AggregateException

Sample

All exceptions are caught and then wrapped in an System.AggregateException which is thrown.

var exceptions = new ConcurrentQueue<Exception>();
Parallel.ForEach(data, d => {
	try 
	{
		if(d < 3) 
			throw new ArgumentException("Value must be greater than 3, Current Value is " + d);
		else
			Console.WriteLine($"d value is {d}");
	}
	catch(Exception e) 
	{
		exceptions.Enqueue(e);
	}
});
if(exceptions.Count > 0)
	throw new AggregateException(exceptions);

Example