Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parallel.ForEach Debug or Step Through

Tags:

Is there an easy way to step through a parallel.foreach? What is the best way to debug this with a break point?

like image 235
Arcadian Avatar asked Jun 19 '12 20:06

Arcadian


People also ask

How do you handle exceptions in parallel ForEach?

For and Parallel. ForEach overloads do not have any special mechanism to handle exceptions that might be thrown. In this respect, they resemble regular for and foreach loops ( For and For Each in Visual Basic); an unhandled exception causes the loop to terminate as soon as all currently running iterations finish.

Is parallel ForEach faster than ForEach?

The execution of Parallel. Foreach is faster than normal ForEach.

Is parallel ForEach blocking?

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


1 Answers

During debug, I'll often setup my Parallel.ForEach to run with MaxDegreeOfParallelism set to 1. This makes it far simpler to debug.

const bool forceNonParallel = true; var options = new ParallelOptions { MaxDegreeOfParallelism = forceNonParallel ? 1 : -1 }; Parallel.ForEach(collection, options, item =>  { //... 

However, this will not help with debugging issues relating to race conditions or data synchronization, and will in fact often hide or eliminate real problems in your code.

Those issues can often be debugged much more easily by using the new tools in VS 2010, such as the Parallel Tasks window, or by using the various techniques listed in Debugging Multithreaded Applications, such as switching threads, locking threads while stepping, etc.

like image 91
Reed Copsey Avatar answered Sep 19 '22 05:09

Reed Copsey