I'm using a Parallel.ForEach
in my code. All my 8 cores go to 100%. This is bad for the other apps that are running on the server. Is it possible to limit execution to like 4 cores?
-
1possible duplicate of Setting the cores to use in Parallelism– Hans PassantApr 1, 2011 at 13:31
3 Answers
Pass an instance of ParallelOptions
with ParallelOptions.MaxDegreeOfParallelism
set to 4 to Parallel.ForEach
.
Nevertheless this might not make sense on other machines, that might have more or less cores than you. In general you should let the framework decide the degree of parallelism.
-
-
@Kees: No, adjusting thread priorities is usually not a good idea. And Tasks are not threads...– H HApr 1, 2011 at 12:07
You can pass in a ParallelOptions
with the MaxDegreeOfParallelism
property set to 4.
-
9Not a good idea to hard-code that '4'.
Environment.ProcessorCount/2
would do better.– H HApr 1, 2011 at 11:50 -
10@Henk: That's hard-coding the 2 :) I was answering the question as asked... exactly how the OP works out how many cores they want is outside the scope, somewhat. (For example, you may want it to go flat-out.) Apr 1, 2011 at 11:55
-
2
Environment.ProcessorCount
returns the number of logical processors, not cores. This is not what Kees needs. For determining the number of cores see stackoverflow.com/questions/1542213/… Apr 1, 2011 at 12:13 -
@all I won't hard-code the number or cores ;-). Looks like a perfect configuration setting. Apr 1, 2011 at 12:42
-
4@Henk: That will run into issues on a single-core machine :) Mar 29, 2013 at 20:45
Here is some code for those who are not satisfied with the other answers
List<int> iList = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8 };
System.Threading.Tasks.ParallelOptions opt = new System.Threading.Tasks.ParallelOptions();
opt.MaxDegreeOfParallelism = 4; // << here the maximum of 4 cores
System.Threading.Tasks.Parallel.ForEach<int>(iList, opt, i =>
{
// do someting with parallelism 4
Console.WriteLine(i);
});