score:1

Accepted answer

You're looking for ParallelEnumerable.AsOrdered:

var result = sequence
    .AsParallel()
    .AsOrdered()
    .Aggregate(seed: string.Empty, func: (prev, current) => prev + current);

The fact that you need to preserve ordering will have a performance hit on your query. As the results need to be aggregated in order, you won't be enjoying the maximum benefit of parallelism, and may sometimes lead to degraded performance over sequential iteration. Having said that, this will do what you're after.

For example, the following code will produce "[7][35][22][6][14]" consistently:

var result = new [] { 35, 14, 22, 6, 7 }
    .AsParallel()
    .AsOrdered()
    .Select(c => "[" + c + "]")
    .Aggregate(seed: string.Empty, func: (prev, current) => prev + current);

Console.WriteLine(result);

There is a good post about PLINQ Ordering by the Parallel Programming Team.


Related Articles