Home > Development > Task Parallel Library – PLINQ Part 1

Task Parallel Library – PLINQ Part 1


We are going to cover the following:

  • Basic data parallelism
  • Configuration Settings

Lets look at basic parallelism. To use PLINQ you need to use the .AsParallel() extension method on IEnumerable<T> which indicates everything following will be ran in parallel. Lets look at some basic code.

Enumerable.Range(1,1000).AsParallel().Sum();

So this is pretty easy. Obviously this is suited to long running operations / computations. If it is small like this its probably going to be quicker to use plain LINQ as there is an overhead in using PLINQ and concurrency in general.

Ok. No we have some of the basics lets look at some tweaks we can apply.
Firstly sometime even though you think the engine will run it in parallel it may not if the enginee thinks parallelizing the query will be slower you can force this using the WithExecutionMode() extension method.
Also if you have a lot of IO bound operations you may want to up the number of work been done in parallel which defaults to you core count. You do do with with SetMaxDegreeOfParallelism() extension method.

More code

items.AsParallel() // Select PLINQ
         .WithExecutionMode(ParallelExecutionMode.ForceParallelism) // Force to run in parallel mode in case sequential selected
         .WithDegreeOfParallelism(6) /
          .Sum();

So there we have some really easy sample to get you of investigation PLINQ.
Next time lets look at Exceptions.

Blair

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: