Search code examples
c#multithreadingplinqconcurrentdictionary

Parallel.ForEach return order by input not by execution into list/dictionary


If you have this:

var resultlist = new List<Dictionary<DateTime, double>>();
Parallel.ForEach(input, item =>
{
    resultlist.Add(SomeDataDictionary(item));
});

The return data will be in the order in which the method SomeDataDictionary returns the data and will not be in the order of the input.

Is there a way to keep the order of input?

Or is the only way to change the datatype and use a Parallel.For loop and then pass the index to some type of array return type?


Solution

  • List<T> is not thread safe, that's why resultlist.Add is incorrect in the context. I suggest using PLinq instead:

     var resultlist = input
       .AsParallel()
       // .AsOrdered() // uncomment this if you want to preserve input order 
       .Select(item => SomeDataDictionary(item))
       .ToList();