微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我们希望可选地控制并行循环中“线程”的数量,以避免压倒Web服务(例如).

是否可以在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);
 });
}

解决方法

你是说按照 MSDN的-1:

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,y => 
//...

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐