Parallel.ForEach有序执行 [英] Parallel.ForEach Ordered Execution

查看:1365
本文介绍了Parallel.ForEach有序执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用新的C#4.0 Parallel.ForEach 函数对对象列表执行并行函数。这是一个非常长的维护过程。我想让它按照列表的顺序执行,以便我可以停止并在上一个点继续执行。我如何做到这一点?

I am trying to execute parallel functions on an list of objects using the new C# 4.0 Parallel.ForEach function. This is a very long maintenance process. I would like to make it execute in the order of the list so that I can stop and continue execution at the previous point. How do I do this?

这是一个例子。我有一个对象列表: a1到a100 。这是目前的顺序:

Here is an example. I have a list of objects: a1 to a100. This is the current order:

a1, a51, a2, a52, a3, a53...

我想要此订单:

a1, a2, a3, a4...

的顺序,但只要我可以在列表中找到一个点,我可以说,在这一点之前的所有对象都运行。我读了并行编程csharp白皮书,没有看到任何东西。在 ParallelOptions 类中没有此设置。

I am OK with some objects being run out of order, but as long as I can find a point in the list where I can say that all objects before this point were run. I read the parallel programming csharp whitepaper and didn't see anything about it. There isn't a setting for this in the ParallelOptions class.

推荐答案

如果使用 Parallel.Break 终止循环,那么您确定所有低于返回值的索引都将被执行。这是关于尽可能接近你可以得到。这里的例子使用For,但ForEach有类似的重载。

If you use Parallel.Break to terminate the loop then you are guarenteed that all indices below the returned value will have been executed. This is about as close as you can get. The example here uses For but ForEach has similar overloads.

int n = ...
var result = new double[n];

var loopResult = Parallel.For(0, n, (i, loopState) =>
{
   if (/* break condition is true */)
   {
      loopState.Break();
      return;
   }
   result[i] = DoWork(i);
});

if (!loopResult.IsCompleted && 
        loopResult.LowestBreakIteration.HasValue)
{
   Console.WriteLine("Loop encountered a break at {0}", 
                      loopResult.LowestBreakIteration.Value);
}

在ForEach循环中,内部为每个元素生成迭代索引划分。执行会发生乱序,但断开后,您知道所有低于 LowestBreakIteration 的迭代都将完成。

In a ForEach loop, an iteration index is generated internally for each element in each partition. Execution takes place out of order but after break you know that all the iterations lower than LowestBreakIteration will have been completed.

摘自使用Microsoft .NET进行并行编程 http://parallelpatterns.codeplex.com/

Taken from "Parallel Programming with Microsoft .NET" http://parallelpatterns.codeplex.com/

在MSDN上可用。请参见 http://msdn.microsoft.com/en-us/library/ff963552。 aspx

Available on MSDN. See http://msdn.microsoft.com/en-us/library/ff963552.aspx. The section "Breaking out of loops early" covers this scenario.

另请参阅: http://msdn.microsoft.com/en-us/library/dd460721.aspx

这篇关于Parallel.ForEach有序执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆