Handling exceptions in parallel loops in .NET C#
April 22, 2014 2 Comments
If a thread in a parallel loop throws an exception then no new iterations will be started. However, iterations already in progress are allowed to run to completion.
You can check if some other iteration has thrown an exception using the the ParallelLoopState class. This class has an IsExceptional property:
Parallel.For(0, 10, (int index, ParallelLoopState state) => { if (state.IsExceptional) { //do something } });
All exceptions throw within the parallel loop are collected within an AggregateException object:
List<int> integers = new List<int>(); for (int i = 0; i <= 100; i++) { integers.Add(i); } try { Parallel.ForEach(integers, (int item, ParallelLoopState state) => { if (item > 50) { throw new ArgumentNullException("Something has happened"); } else { Console.WriteLine("Less than 50: {0}", item); } if (state.IsExceptional) { Console.WriteLine("Exception!"); } }); } catch (AggregateException ae) { ae.Handle((inner) => { Console.WriteLine(inner.Message); return true; }); }
You can read more about handling exceptions throw by tasks here, here and here.
Please view the comment section for a link with another example.
View the list of posts on the Task Parallel Library here.
How about collecting in a blocking collection the exceptions inside the foreach and aggregate? http://msdn.microsoft.com/en-us/library/dd460695(v=vs.110).aspx
Adi, thanks for the tip, I’ll update the post with your link.
//Andras