Is there an easy way to step through a parallel.foreach? What is the best way to debug this with a break point?
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.
The execution of Parallel. Foreach is faster than normal ForEach.
No, it doesn't block and returns control immediately. The items to run in parallel are done on background threads.
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.
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