Question

I am looking at this code

var numbers = Enumerable.Range(0, 20);
var parallelResult = numbers.AsParallel().AsOrdered()
    .Where(i => i % 2 == 0).AsSequential();

foreach (int i in parallelResult.Take(5))
    Console.WriteLine(i);

The AsSequential() is supposed to make the resulting array sorted. Actually it is sorted after its execution, but if I remove the call to AsSequential(), it is still sorted (since AsOrdered()) is called.

What is the difference between the two?

Was it helpful?

Solution

AsSequential is just meant to stop any further parallel execution - hence the name. I'm not sure where you got the idea that it's "supposed to make the resulting array sorted". The documentation is pretty clear:

Converts a ParallelQuery into an IEnumerable to force sequential evaluation of the query.

As you say, AsOrdered ensures ordering (for that particular sequence).

OTHER TIPS

I know that this was asked over a year old but here are my two cents.

In the example exposed, i think it uses AsSequential so that the next query operator (in this case the Take operator) it is execute sequentially.

However the Take operator prevent a query from being parallelized, unless the source elements are in their original indexing position, so that is why even when you remove the AsSequential operator, the result is still sorted.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top