The MSDN page does not really state what happens when ParallelOptions.MaxDegreesOfParallelism
equals 1
.
I make extensive use of the Parallel
loops and I would like to debug it when it runs synchronously / single threaded.
I was wondering if I need to convert the Parallel
loops to regular for/each
loops manually or whether I can set the MaxDegreesOfParallelism
to 1 to run it on the calling thread instead.
The order in my operations do not matter, I am aware that Parallel
does not make any guarantees about the order of execution.
The
Parallel.ForEach
method uses the current thread as one of the worker threads. By configuring theMaxDegreesOfParallelism
with the value1
, most likely all the work will be carried out by the current thread alone, without involving theThreadPool
at all. Nevertheless this behavior is not explicitly specified in the official documentation. If you absolutely want this guarantee, you can either delve into the source code and derive this guarantee by examining the implementation (and do it again each time a new .NET version is released), or switch to a simpleforeach
loop. The source code of theParallel
class is quite lengthy and convoluted, so if I was in your shoes I would pick the second option.