Using AsSequential to maintain order

I look 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); 

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

What is the difference between the two?

+7
c # plinq task-parallel-library
source share
2 answers

AsSequential intended only to stop further parallel execution - hence the name. I'm not sure where you have the idea that it "should make a sorted array sorted". The documentation is pretty straightforward:

Converts ParallelQuery to IEnumerable to force sequential query evaluation.

As you say, AsOrdered provides ordering (for this particular sequence).

+10
source share

I know this was asked for a year, but here are my two cents.

In the example shown, I think it uses AsSequential so that the next query statement (in this case, the Take statement) is executed sequentially.

However, the Take statement prevents query parallelization if the original elements are not in the initial indexing position, so even when you delete the AsSequential statement, the result is still sorted.

+2
source share

All Articles