My previous post discussed the TPL library and its uses to create scalable applications. Another way to incorporate the parallel task into your .Net applications is through PLINQ.
LINQ queries that are designed to run in Parallel are termed PLINQ queries.
The framework of PLINQ has been optimized in such a way that it includes determining if a query can perform faster in a synchronous manner. Is analyze the LINQ query at run time if it's likely to benefit from parallelization when run concurrently.
The TPL library provides the following methods to support the parallel LINQ queries.
AsParallel()
Specifies that the rest of the query should be parallelized, if possible.
WithCancellation()
Specifies that PLINQ should periodically check for the state of the provided CancellationToken and cancel execution if it is required.
WithDegreeOfParallelism()
Specifies the maximum number of processors that PLINQ should use to parallelize the query.
ForAll()
Enables results to be processed in parallel without first merging back to the consumer thread, as would be the case when enumerating a LINQ result using the foreach keyword.
Let's see the demo:
Creating the first PLINQ query:
If you want to use TPL to execute your query in parallel (if possible), then you will want to use the AsParallel() extension method:
-
- int[] modeThreeIsZero = (from num in source.AsParallel()
- where (num % 3) == 0
- orderby num descending
- select num).ToArray();
Here is the complete code:
- namespace PLINQ_Demo {
- class Program {
- static DateTime startTime;
- static void Main(string[] args) {
- ProcessIntDataNormalMode();
- ProcessIntDataNormalMode();
- Console.ReadLine();
- }
-
- private static void ProcessIntDataNormalMode() {
-
- startTime = DateTime.Now;
-
-
- int[] source = Enumerable.Range(1, 10000000).ToArray();
-
-
- int[] modeThreeIsZero = (from num in source.AsParallel() where(num % 3) == 0 orderby num descending select num).ToArray();
-
- TimeSpan ts = DateTime.Now.Subtract(startTime);
-
-
- Console.WriteLine("{0} numbers found as result. \n Time Elapsed: {1} Seconds:MilliSeconds in Normal mode", modeThreeIsZero.Count(), ts.Seconds + ":" + ts.Milliseconds);
- }
-
- private static void ProcessIntDataParallelMode() {
-
- startTime = DateTime.Now;
-
-
- int[] source = Enumerable.Range(1, 10000000).ToArray();
-
-
- int[] modeThreeIsZero = (from num in source.AsParallel() where(num % 3) == 0 orderby num descending select num).ToArray();
-
-
- TimeSpan ts = DateTime.Now.Subtract(startTime);
-
- Console.WriteLine("{0} numbers found as result \n Time Elapsed: {1} [Seconds:MilliSeconds] in parallel mode.", modeThreeIsZero.Count(), ts.Seconds + ":" + ts.Milliseconds);
- }
- }
- }