3

Let imagine that I have a Parallel.ForEach running in my code with the ParallelOption MaxDegreeOfParallelism set to Utils.Threads() like that :

Parallel.ForEach(linesList, new ParallelOptions { MaxDegreeOfParallelism = Utils.Threads() }, line => ...

Now imagine that Utils.Threads() is returning a random integer between 1 and 10.

Will the MaxDegreeOfParallelism change while my Parallel.ForEach is running, or will it be set to the first Utils.Threads() call for all the time ? Thanks in advance.

  • I'm venturing a guess that you can't modify this once it's initialized. I read the msdn page and couldn't find anything mentioning you could (or couldn't), but I'd err on the side that you can't. – mariocatch May 06 '18 at 03:47

1 Answers1

1

Will the MaxDegreeOfParallelism change while my Parallel.ForEach is running, or will it be set to the first Utils.Threads() call for all the time ? Thanks in advance.

No it wouldn't, since it doesn't keep checking and modifying the assigned value, which is required during API initialization. Infact if you review the signature of MaxDegreeOfParallelism,

public int MaxDegreeOfParallelism { get; set; }

since its a value type not a reference type, its integer, so in any case, value is copied it is never referred for any change in value, standard behavior of the value types

Impact of MaxDegreeOfParallelism on Parallel.ForEach call

Its an indicator or the hint, it doesn't ensure that many parallel threads are provisioned from the pool before execution starts. For Parallel.ForEach it always starts with single thread and keep appending the ability to execute in parallel depending upon the number of tasks and amount of time they take. This value is also internally moderated, its not that you can provide a very high value and expect that many threads to be provisioned. It though behaves differently in case of PLinq, where before processing it would expect most of threads to be provisioned / initialized, but it can have an adverse performance impact, if there's not enough work for each thread, due to context switching

Couple of reference links, regarding DOP in C# Parallel / PLinq API:

When to set the max degree of parallelism

Max Degree of Parallelism for AsParallel()

Mrinal Kamboj
  • 11,300
  • 5
  • 40
  • 74
  • Very nice answer, helped me understanding it a lot more better ! Since you seem pretty good about this subject, is there an other way than Parallel.ForEach to do the same thing I'm doing actually with my list ? Thanks ! – user9331278 May 06 '18 at 07:16
  • Welcome, another important point, since `MaxDegreeOfParallelism`, is a value type, `int`, so in any case value is copied once it cannot be referred back for any change, that can happen only for reference type – Mrinal Kamboj May 06 '18 at 08:47