Reputation: 45
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.
Upvotes: 4
Views: 1481
Reputation: 11478
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
onParallel.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()
Upvotes: 2