Converting a LINQ query to PLINQ
Posted by: Suprotim Agarwal ,
on 7/3/2011,
in
Category LINQ
Abstract: PLINQ provides support for Parallel programming and is closely related to the Task Parallel Library. In very simple words, PLINQ enables a query to automatically take advantage of multiple processors. In this article, we will see a simple example of transforming a LINQ query to PLINQ.
PLINQ provides support for Parallel programming and is closely related to the Task Parallel Library. In very simple words, PLINQ enables a query to automatically take advantage of multiple processors.
In my 50 LINQ Examples, Tips and How To's article, a www.dotnetcurry.com reader Mike Long commented that he wanted to see a simple example of transforming a LINQ query to PLINQ. In this short article, I will demonstrate the same.
Let us first compare these 2 pieces of code:
Sequential LINQ

Parallel LINQ

In the query above, we first use Enumerable.Range method to generate a sequence of large integral numbers within a specified range. We then select and print numbers divisible by 1234567. We print the time elapsed using the Stopwatch class.
In the second query, as you can observe, it so easy to create a Parallel query. All we have to do is simply call AsParallel( ) on the data source i.e. on ‘rng’ and a sequential LINQ query is transformed into a parallel PLINQ query. This enables parallel operations on the data. Internally the data source is partitioned and the query operates on each partition in parallel. In case parallelization is not possible, the query is executed sequentially.
Tip: You can print the Thread.CurrentThread.ManagedThreadId and observe the differences between the output. The ThreadID in case of parallel execution will be different.
OUTPUT

On the same note, you may also want to see LINQ: Generate Odd Numbers using Parallel Execution
Give me a +1 if you think it was a good article. Thanks!