Parallel.ForEach同时保留订单

Mat*_*olf 7 c# collections parallel-processing concurrency asynchronous

我有一个List<byte[]>,我喜欢将每个反序列byte[]化为Foo.列表是有序的,我喜欢写一个并行循环,其中结果List<Foo>包含所有Foo的顺序与原始顺序相同byte[].该列表非常大,可以使并行操作变得有价值.有没有内置的方法来实现这一目标?

如果没有,任何想法如何实现同步运行这一切的加速?

谢谢

Dr.*_*ABT 9

从你给出的信息中,我知道你想要一个Foo的输出数组,其大小等于输入的字节数组?它是否正确?

如果是这样,是的,操作很简单.不要理会锁定或同步构造,这些会侵蚀并行化带给您的所有速度.

相反,如果遵守这个简单的规则,任何算法都可以并行化,而无需锁定或同步:

对于处理的每个输入元素X [i],您可以从任何输入元素X [j]读取,但只写入输出元素Y [i]

在此输入图像描述

查找Scatter/Gather,这种类型的操作称为聚集,因为只写入一个输出元素.

如果你可以使用上面的原则,那么你想要在前面创建输出数组Foo [],并在输入数组上使用Parallel.For not ForEach.

例如

        List<byte[]> inputArray = new List<byte[]>();
        int[] outputArray = new int[inputArray.Count];

        var waitHandle = new ManualResetEvent(false);
        int counter = 0;

        Parallel.For(0, inputArray.Count, index =>
            {
                // Pass index to for loop, do long running operation 
                // on input items
                // writing to only a single output item
                outputArray[index] = DoOperation(inputArray[index]);

                if(Interlocked.Increment(ref counter) == inputArray.Count -1)
                {
                    waitHandle.Set();
                }
            });

        waitHandler.WaitOne();

        // Optional conversion back to list if you wanted this
        var outputList = outputArray.ToList();
Run Code Online (Sandbox Code Playgroud)