Converting a LINQ query to PLINQ
Posted by: Suprotim Agarwal
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:
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.
On the same note, you may also want to see LINQ: Generate Odd Numbers using Parallel Execution
This article has been editorially reviewed by Suprotim Agarwal.
C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.
We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).
Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.
Click here to Explore the Table of Contents or Download Sample Chapters!