Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle exceptions in Parallel.ForEach?

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?

like image 916
Piguy Avatar asked Oct 20 '16 08:10

Piguy


People also ask

Is parallel ForEach blocking?

No, it doesn't block and returns control immediately. The items to run in parallel are done on background threads.

Does ForEach work in parallel?

ForEach Method (System. Threading. Tasks) Executes a foreach (For Each in Visual Basic) operation in which iterations may run in parallel.

Is parallel ForEach multithreaded?

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.

How do you continue in parallel ForEach?

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.


1 Answers

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.

like image 73
Henk Holterman Avatar answered Oct 05 '22 04:10

Henk Holterman