Handling exceptions in parallel LINQ in .NET C#
May 6, 2014 1 Comment
We saw in this and this post how to handle exceptions that Tasks throw. It is not much different in parallel LINQ: the exception will be wrapped in an AggregateException.
The exception will be throw when the query is executed. So defining a parallel query will not throw an exception even if you explicitly throw one within the query. If you force the execution of the query with extension methods such as ToList, ToArray, ForAll etc., then the exception will be thrown immediately. Let’s see an example.
Define the data source:
int[] integerArray = new int[100]; for (int i = 0; i < integerArray.Length; i++) { integerArray[i] = i; }
Define the query:
IEnumerable<double> query = integerArray.AsParallel() .Select(item => { if (item == 50) { throw new Exception(); } return Math.Sqrt(item); });
Go through the results and handle the exception:
try { foreach (double item in query) { Console.WriteLine("Result {0}", item); } } catch (AggregateException aggregateException) { aggregateException.Handle(exception => { Console.WriteLine("Handled exception of type: {0}", exception.GetType()); return true; }); }
Run the code with Crtl+F5. You’ll see that the exception is thrown when the items are processed and then it’s handled. Items that were processed when the exception was thrown will complete so don’t assume that the parallel loop is interrupted at that moment.
View the list of posts on the Task Parallel Library here.
To handle nested aggregateexceptions u can use aggregateException.Flatten().Handle()