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?
Asked
Active
Viewed 2.0k times
48

Kees C. Bakker
- 32,294
- 27
- 115
- 203
-
1possible duplicate of [Setting the cores to use in Parallelism](http://stackoverflow.com/questions/2956670/setting-the-cores-to-use-in-parallelism) – Hans Passant Apr 01 '11 at 13:31
3 Answers
44
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.

Florian Greinacher
- 14,478
- 1
- 35
- 53
-
See http://stackoverflow.com/questions/1542213/how-to-find-the-number-of-cpu-cores-via-net-c – Florian Greinacher Apr 01 '11 at 10:57
-
@Kees: No, adjusting thread priorities is usually not a good idea. And Tasks are not threads... – H H Apr 01 '11 at 12:07
27
You can pass in a ParallelOptions
with the MaxDegreeOfParallelism
property set to 4.

Jon Skeet
- 1,421,763
- 867
- 9,128
- 9,194
-
10Not a good idea to hard-code that '4'. `Environment.ProcessorCount/2` would do better. – H H Apr 01 '11 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.) – Jon Skeet Apr 01 '11 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 http://stackoverflow.com/questions/1542213/how-to-find-the-number-of-cpu-cores-via-net-c – Florian Greinacher Apr 01 '11 at 12:13
-
@all I won't hard-code the number or cores ;-). Looks like a perfect configuration setting. – Kees C. Bakker Apr 01 '11 at 12:42
-
@FlorianGreinacher: Actually the number of logical processors *is* what he would want... – BlueRaja - Danny Pflughoeft Mar 29 '13 at 20:44
-
4@Henk: That will run into issues on a single-core machine :) – BlueRaja - Danny Pflughoeft Mar 29 '13 at 20:45
15
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);
});

fubo
- 44,811
- 17
- 103
- 137