In my previous article, Parallel Extension in .NET I have explained how we can leverage the same with the help of a parallel loop.
In this article, I will explain how we can utilize the same with the help of PLINQ.
Prerequisite to follow steps this articles are :
-
Follow my first article Parallel Extension in .NET to set up environment to use this extension.
Have basic knowledge of LINQ. To learn more about LINQ, visit LINQ section here.
Once we have our environment all setup, let's get back to our topic. We can implement PLINQ in two ways.
-
By using System.Linq.ParallelEnumerable class.
-
By using The AsParallel extension method, exposed from the System.Linq.ParallelQuery class.
Before moving forward let me advise you to use Parallel Linq only for the linq queries which query large amounts of data, perform expensive computations, or a combination of both.
Example of using System.Linq.ParallelEnumerable class
Let's take a look at this sample code in Linq
return (from i in Enumerable.Range(0, m_yValues.Length - 1)
select ComputeUnionAreaWithinStrip(i))
.Sum();
With the Help of PLINQ same statement could have been written as this
return (from i in ParallelEnumerable.Range(0, m_yValues.Length - 1)
select ComputeUnionAreaWithinStrip(i))
.Sum();
Example of using AsParallel extension method
Let's take a look at this sample code in Linq
public static int CountValidISBNsSequential(IEnumerable source)
{
return source.Where(s => isValidISBN(s)).Count();
}
With the help of PLINQ, the same statement could have been written as this
public static int CountValidISBNsParallel(IEnumerable source)
{
return source.AsParallel().Where(s => isValidISBN(s)).Count();
}
Notice the Method AsParallel( ) in the above code snippet.
I will add more about this Parallel Extension in my next article.