Parallel LINQ in .NET C#: keeping the order

In this post we saw a simple example of PLINQ. We saw that the items are processed in an arbitrary order.

Consider the following:

int[] sourceData = new int[10];
for (int i = 0; i < sourceData.Length; i++)
{
	sourceData[i] = i;
}

IEnumerable<int> parallelResults =
	from item in sourceData.AsParallel()
	where item % 2 == 0
	select item;

foreach (int item in parallelResults)
{
	Console.WriteLine("Item {0}", item);
}

When I ran the code on my machine I got the following output:

0, 4, 6, 8, 2

What if you want the items to be processed in an ascending order? Just append the AsOrdered() extension method:

IEnumerable<int> parallelResults =
	from item in sourceData.AsParallel().AsOrdered()
	where item % 2 == 0
	select item;

This produces the same order as a sequential query execution but with the benefits of parallel execution. However, there’s a small cost to this. Without ordering PLINQ could freely decide how to start and optimise the threads. Now there’s a performance cost to restore the order with the AsOrdered extension method. Keep this in mind and only use ordering if it really matters. Otherwise you can order the resulting list with “normal” LINQ afterwards.

View the list of posts on the Task Parallel Library here.

Advertisements

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

ultimatemindsettoday

A great WordPress.com site

Elliot Balynn's Blog

A directory of wonderful thoughts

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT BEST PRACTICES WITH MICROSOFT STACK & ANGULAR

Cyber Matters

Bite-size insight on Cyber Security for the not too technical.

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: