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?
No, it doesn't block and returns control immediately. The items to run in parallel are done on background threads.
ForEach Method (System. Threading. Tasks) Executes a foreach (For Each in Visual Basic) operation in which iterations may run in parallel.
Parallel. ForEach is like the foreach loop in C#, except the foreach loop runs on a single thread and processing take place sequentially, while the Parallel. ForEach loop runs on multiple threads and the processing takes place in a parallel manner.
When you converted your loop into a compatible definition for the Parallel. Foreach logic, you ended up making the statement body a lambda. Well, that is an action that gets called by the Parallel function. So, replace continue with return , and break with Stop() or Break() statements.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With