c# - Parallel.ForEach 同时保留顺序

标签 c# collections asynchronous concurrency parallel-processing

我有一个 List<byte[]>我喜欢反序列化每个 byte[]进入福。 List 是有序的,我喜欢编写一个并行循环,其中生成的 List<Foo>以与原始 byte[] 相同的顺序包含所有 Foo .该列表非常大,使并行操作值得。有没有内置的方法来完成这个?

如果没有,有什么想法可以通过同步运行来实现加速吗?

谢谢

最佳答案

根据您提供的信息,我了解到您想要一个大小等于输入字节数组的 Foo 输出数组?这样对吗?

如果是这样,是的,操作很简单。不要为锁定或同步构造而烦恼,它们会侵 eclipse 并行化为您提供的所有速度。

相反,如果您遵守这个简单的规则,任何算法都可以在没有锁定或同步的情况下并行化:

For each input element X[i] processed, you may read from any input element X[j], but only write to output element Y[i]

enter image description here

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

如果您可以使用上述原则,那么您希望预先创建输出数组 Foo[],并在输入数组上使用 Parallel.For 而不是 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();

关于c# - Parallel.ForEach 同时保留顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11115049/

相关文章:

java - hibernate/Ehcache : evicting collections from 2nd level cache not synchronized with other DB reads

node.js - 在运行测试之前, Mocha 似乎不会等待 promise 链完成

javascript - 您如何调试 Javascript 中的时序问题?

c# - 什么 C# 类型代表 C++ float*?

c# - Asp.net core 2 CORS预检请求响应缓慢

c# - 这样的集合是否存在(Dictionary 和 HashSet 的功能)?

c# - 匿名异步,怎样才是正确的做法?

C# 使用 XSD 架构作为表单的元数据

c# - 无法找到 pdb 文件

c# - 可以将内部 List<T> 作为 IEnumerable<T> 或 ICollection<T> 返回吗?