Is it possible to limit the cores for Parallel.ForEach?

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.


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


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);
});