How to: Specify the Execution Mode in PLINQ
This example shows how to force PLINQ to bypass its default heuristics and parallelize a query regardless of the query's shape.
This example is intended to demonstrate usage, and might not run faster than the equivalent sequential LINQ to Objects query. For more information about speedup, see Understanding Speedup in PLINQ.
PLINQ is designed to exploit opportunities for parallelization. However, not all queries benefit from parallel execution. For example, when a query contains a single user delegate that does very little work, the query will usually run faster sequentially. This is because the overhead involved in enabling parallelizing execution is more expensive than the speedup that is obtained. Therefore, PLINQ does not automatically parallelize every query. It first examines the shape of the query and the various operators that comprise it. Based on this analysis, PLINQ in the default execution mode may decide to execute some or all of the query sequentially. However, in some cases you may know more about your query than PLINQ is able to determine from its analysis. For example, you may know that a delegate is very expensive, and that the query will definitely benefit from parallelization. In such cases, you can use the WithExecutionMode<TSource> method and specify the ForceParallelism value to instruct PLINQ to always run the query as parallel.