Ordered PLINQ ForAll

Steven Jeuris picture Steven Jeuris · Mar 18, 2011 · Viewed 7.8k times · Source

The msdn documentation about order preservation in PLINQ states the following about ForAll().

  • Result when the source sequence is ordered: Executes nondeterministically in parallel
  • Result when the source sequence is unordered: Executes nondeterministically in parallel

Does this mean that ordered execution of the ForAll method is never guaranteed?

I haven't used PLINQ before, but the following Code Review question seemed like an appropriate usage for it. At the bottom of my answer I write:

Events.AsParallel().AsOrdered().ForAll( eventItem =>
{
    ...
} );    

After reading the documentation I believe the AsOrdered() wouldn't change anything?
I'm also suspecting the previous query can't replace a simple for loop where order is important?
Probably parallel calls to the StringBuilder will also occur, resulting in a wrong output?

Answer

Jon Skeet picture Jon Skeet · Mar 18, 2011

Order preservation is usually only applied to results - i.e. the input can be processed in any order, but is returned in the original order.

As ForAll doesn't return anything, it doesn't really have any effect that I'm aware of.

The only way of making ordering apply to the processing would be to finish item 0 before processing item 1, before processing item 2 etc... at which point you've got no parallelism.