LINQ queries which are designed to run in Parallel are termed as 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 its 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 o fthe 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 see the demo
Creating first PLINQ query:
if you want to use TPL to execute your query in parallel(if possible), 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 to process and random array and analyze the Execution time:
- namespace PLINQ_Demo
- {
- class Program
- {
- static DateTime startTime;
- static void Main(string[] args)
- {
- ProcessIntDataNormalMode();
- ProcessIntDataParallelMode();
- Console.ReadLine();
- }
- private static void ProcessIntDataNormalMode()
- {
- //record current time
- startTime = DateTime.Now;
- //Get a random large array of integers
- int[] source = Enumerable.Range(1, 10000000).ToArray();
- //Prepare the query
- int[] modeThreeIsZero = (from num in source.AsParallel()
- where (num % 3) == 0
- orderby num descending
- select num).ToArray();
- //timer
- TimeSpan ts = DateTime.Now.Subtract(startTime);
- //Process and show the result
- 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()
- {
- //record current time
- startTime = DateTime.Now;
- //Get a random large array of integers
- int[] source = Enumerable.Range(1, 10000000).ToArray();
- //Prepare the query
- int[] modeThreeIsZero = (from num in source.AsParallel()
- where (num % 3) == 0
- orderby num descending
- select num).ToArray();
- //timer
- TimeSpan ts = DateTime.Now.Subtract(startTime);
- //Process and show the result
- Console.WriteLine("{0} numbers found as result \n Time Elapsed: {1} [Seconds:MilliSeconds] in parallel mode.", modeThreeIsZero.Count(), ts.Seconds + ":" + ts.Milliseconds);
- }
- }
- }
Output:
Let my code to choose if CPU cores can be uitilized!
No comments:
Post a Comment