Parallel .ForEach while maintaining order

I have List<byte[]>and I like to deserialize everyone byte[]in Foo. The list is ordered, and I like to write a parallel loop in which the received List<Foo>contains all Foo in the same order as the original one byte[]. The list is significantly large to make the parallel work worthwhile. Is there a built-in way to do this?

If not, any ideas on how to speed up this synchronously?

thank

+5
source share
2 answers

From the information you provided, I understand that you want to have an Foo output array with a size equal to the input byte array? It's right?

, . , , .

, , :

X [i] X [j], Y [i]

enter image description here

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();
+5

int foo

+2

All Articles