How to handle exceptions in Parallel.ForEach?

.net, c#, exception, task-parallel-library

Solution

Should I catch and handle exceptions inside the loop or should I catch aggregate exception outside

Those two are not functionally equivalent. Both can be done, with different effects.

The fundamental question is: when one or more iterations suffer an exception, do you want the remaining items to be processed or not?

If yes, then handle them inside the loop, possibly storing them like in the MSDN example. If not then just put a try/catch around the Parallel loop itself.

Problem

I have a `Parallel.ForEach` loop in my code and I am wondering how to handle exceptions. Should I catch and handle(e.g write to log) exceptions inside the loop or should I catch aggregate exception outside - encapsulate the loop in try/catch?

Original source