gpt4 book ai didi

c# - 在 Parallel.ForEach 中指定默认的 MaxDegreeOfParallelism?

转载 作者:行者123 更新时间:2023-11-30 14:09:48 28 4
gpt4 key购买 nike

我们希望有选择地控制并行循环中“线程”的数量,以避免网络服务不堪重负(例如)。

是否可以在 Parallel.ForEach 循环中指定自定义 MaxDegreeOfParallelism,但也可以根据需要恢复为默认值?看似零 (0) 是 MaxDegreeOfParallelism 的无效值,而我希望它可以简单地表示“忽略”。

换句话说,你能避免写这种类型的代码吗?

int numParallelOperations = GetNumParallelOperations();
if (numParallelOperations > 0)
{
ParallelOptions options = new ParallelOptions();
options.MaxDegreeOfParallelism = numParallelOperations;
Parallel.ForEach(items, options, i =>
{
Foo(i);
});
}
else
{
Parallel.ForEach(items, i =>
{
Foo(i);
});
}

最佳答案

你是说 -1 根据 MSDN :

The MaxDegreeOfParallelism limits the number of concurrent operations run by Parallel method calls that are passed this ParallelOptions instance to the set value, if it is positive. If MaxDegreeOfParallelism is -1, then there is no limit placed on the number of concurrently running operations.

您可以像这样控制近似线程数:

// use only (ca) one kernel:
int degreeOfParallelism = 1;
// leave (ca) one kernel idle:
int degreeOfParallelism = Environment.ProcessorCount - 1;
// use (ca) half of the kernels:
int degreeOfParallelism = Environment.ProcessorCount > 1 ?
Environment.ProcessorCount / 2 : 1;
// run at full speed:
int degreeOfParallelism = - 1;

var options = new ParallelOptions();
options.MaxDegreeOfParallelism = degreeOfParallelism;

Parallel.For(0, x, options, y =>
//...

关于c# - 在 Parallel.ForEach 中指定默认的 MaxDegreeOfParallelism?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27538057/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com