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

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

问题描述

我正在尝试使用新的 C# 4.0 Parallel.ForEach 函数在对象列表上执行并行函数.这是一个很长的维护过程.我想让它按照列表的顺序执行,这样我就可以在上一点停止并继续执行.我该怎么做呢?

I am trying to execute parallel functions on a 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.

推荐答案

做这样的事情:

int current = 0;
object lockCurrent = new object();

Parallel.For(0, list.Count, 
             new ParallelOptions { MaxDegreeOfParallelism = MaxThreads },
             (ii, loopState) => {
                    // So the way Parallel.For works is that it chunks the task list up with each thread getting a chunk to work on...
                    // e.g. [1-1,000], [1,001- 2,000], [2,001-3,000] etc...
                    // We have prioritized our job queue such that more important tasks come first. So we don't want the task list to be
                    // broken up, we want the task list to be run in roughly the same order we started with. So we ignore tha past in 
                    // loop variable and just increment our own counter.
                    int thisCurrent = 0;
                    lock (lockCurrent) {
                        thisCurrent = current;
                        current++;
                    }
                    dothework(list[thisCurrent]);
                 });

您可以看到当您退出并行 for 循环时,您将如何知道要执行的最后一个列表项,假设您让所有线程在中断之前完成.我不是 PLINQ 或 LINQ 的忠实粉丝.老实说,我不明白编写 LINQ/PLINQ 如何导致可维护的源代码或可读性......Parallel.For 是一个更好的解决方案.

You can see how when you break out of the parallel for loop you will know the last list item to be executed, assuming you let all threads finish prior to breaking. I'm not a big fan of PLINQ or LINQ. I honestly don't see how writing LINQ/PLINQ leads to maintainable source code or readability.... Parallel.For is a much better solution.

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

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