Parallel LINQ looks for opportunities to parallelize a query, but not all queries run faster in parallel. For example, a query that contains a single delegate that does only a little bit of work will usually run faster sequentially, because the overhead of parallelizing outweighs the benefits gained from parallelizing it.
For the most part, parallel LINQ does a really good job of determining what should be parallelized and what should run sequentially, based on its examination of the shape of the query. However, the algorithm it uses is not perfect, and you might need to instruct PLINQ to run your query in parallel.
In this recipe, we will build a Console
application that creates a query which PLINQ will determine whether it needs to be executed sequentially. We will then force the query to run in parallel using the WithExecutionMode
method. Finally, we will capture the time it takes for both queries to run and compare the results.