I'm refactoring code that was written some time ago when linq and delegates didn't exist and a lot of the code is embarrassingly parallelizable so I'm using AsParallel
whenever I can but I'm not quite sure what happens when ordered lists are involved in such queries. For example,
/* suppose we have the following list
SortedList<DateTime, SomeClass> list1
*/
var projection = list1.AsParallel().Select(t => t.Key);
var skippedProjection = list1.AsParallel().Select(t => t.Key).Skip(1);
var zipped = projection.AsParallel().Zip(skippedProjection, someComputation);
My question is the following: Is the ordering preserved in parallel queries? In other words will the above example work as I expect or will the Select
queries following AsParallel
return things in random order depending on what strategy is used behind the scenes?
In general, using AsParallel()
will cause the results to be unordered. That being said, you can explicitly specify that you require ordering by adding a call to AsOrdered. For example:
var zipped = projection.AsParallel().AsOrdered().Zip(skippedProjection, someComputation);
Some operations handle ordering automatically, so this is not always required - but enforcing order will slow down the operation and/or reduce the amount of parallelism, so it's typically not the default.
For details, I recommend reading Order Preservation in PLINQ. That article discusses the details of what preserves order and what does not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With