Search code examples
c#task-parallel-libraryparallel.foreachparallel.for

Do Parallel Loops with MaxDegreesOfParallelism = 1 run on the calling thread?


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.


Solution

  • The Parallel.ForEach method uses the current thread as one of the worker threads. By configuring the MaxDegreesOfParallelism with the value 1, most likely all the work will be carried out by the current thread alone, without involving the ThreadPool 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 simple foreach loop. The source code of the Parallel class is quite lengthy and convoluted, so if I was in your shoes I would pick the second option.