Parallel.ForEach Ordered Execution

后端 未结 6 1766
猫巷女王i
猫巷女王i 2020-12-10 11:10

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

6条回答
  •  情话喂你
    2020-12-10 12:06

    Do something like this:

    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]);
                     });
    

    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.

提交回复
热议问题