In continuation to my 100DaysOfCoding, in this post I will talk about Parallel LINQ. Parallel Language-Integrated Query(PLINQ) can be used to allow elements of a query to execute in parallel. Below is a snippet of code which consists of an array of persons.
AsParallel
Using PLINQ we are selecting the records where the person city is Seattle and also we used AsParallel method. AsParallel method will examine if running parallelly improves the query performance. If it finds that improves performance query is executed parallelly by breaking down into smaller process and running concurrently. In case where it could not determine if running parallelly improves performance then it doesn’t execute in parallel. This is the reason when using AsParallel the design of the query should be made keeping performance in mind.
Forcing Paralleization
When using AsParallel we can force parallelization irrespective of the performance. This can be achieved by stating explicitly the execution mode as ForceParallelism and also the degree of parallelism. The degree indicates the maximum number of processors which can be used for execution. Below is an example which explicitly states parallelization with a maximum of four processors to be used for execution.
AsOrdered
When running query parallelly the output data of the query will not be in the same order of input. To achieve that we can use AsOrdered method. This would still execute the query parallelly but arranges the result to be in order of the input. Using AsOrdered can have a performance impact. Below is an example of AsOrdered in use.
AsSequential
When running complex queries parallelly it may remove the ordering of the query. To achieve that AsSequential method can be used . Below example shows the use of AsSequential
The query in the example retrieves the names of the first four people who live in Seattle. The query requests that the result be ordered by person name, and this ordering is preserved by the use of AsSequential before the Take, which removes the four people. If the Take is executed in parallel it can disrupt the ordering of the result.
ForAll
The ForAll method is used to iterate through all the elements of the query. Difference between ForEach and ForAll is that it executes the iteration parallelly and it starts the execution before the query is even complete. Below example shows ForAll in use.
Exceptions in queries
If any queries generate exceptions an AggregateException will be thrown when the query is complete. This contains a list, InnerExceptions, of the exceptions that were thrown during the query. Below is an example where the exceptions thrown by CheckCity method when the city value is empty are caught.
GitHub Link: Parallel LINQI couldn’t hit gym today but I played badminton, which to me is still a Fitness activity :-p
#Day2Of100DaysOfCoding #Day2Of100DaysOfFitness
Comments