Parallel.ForEach Debug or Step Through

Arcadian picture Arcadian · Jun 19, 2012 · Viewed 13.6k times · Source

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

Answer

Reed Copsey picture Reed Copsey · Jun 19, 2012

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.