48

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?

Kees C. Bakker
  • 32,294
  • 27
  • 115
  • 203
  • 1
    possible 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 Answers3

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
27

You can pass in a ParallelOptions with the MaxDegreeOfParallelism property set to 4.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
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