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?
我在我的代码中使用了Parallel.ForEach。我的所有8个内核都达到了100%。这对于在服务器上运行的其他应用程序来说很糟糕。是否可以将执行限制为4核心?
3 个解决方案
#1
40
Pass an instance of ParallelOptions
with ParallelOptions.MaxDegreeOfParallelism
set to 4 to Parallel.ForEach
.
将ParallelOptions的实例与ParallelOptions.MaxDegreeOfParallelism设置为4并传递给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.
然而,这可能在其他机器上没有意义,这些机器可能具有比您更多或更少的核心。通常,您应该让框架决定并行度。
#2
24
You can pass in a ParallelOptions
with the MaxDegreeOfParallelism
property set to 4.
您可以将MaxDegreeOfParallelism属性设置为4传递ParallelOptions。
#3
10
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);
});
#1
40
Pass an instance of ParallelOptions
with ParallelOptions.MaxDegreeOfParallelism
set to 4 to Parallel.ForEach
.
将ParallelOptions的实例与ParallelOptions.MaxDegreeOfParallelism设置为4并传递给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.
然而,这可能在其他机器上没有意义,这些机器可能具有比您更多或更少的核心。通常,您应该让框架决定并行度。
#2
24
You can pass in a ParallelOptions
with the MaxDegreeOfParallelism
property set to 4.
您可以将MaxDegreeOfParallelism属性设置为4传递ParallelOptions。
#3
10
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);
});