Redaguoti

Bendrinti naudojant


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.

Note

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.

Example

// Paste into PLINQDataSample class.
static void ForceParallel()
{
    var customers = GetCustomers();
    var parallelQuery = (from cust in customers.AsParallel()
                            .WithExecutionMode(ParallelExecutionMode.ForceParallelism)
                         where cust.City == "Berlin"
                         select cust.CustomerName)
                        .ToList();
}
Private Shared Sub ForceParallel()
    Dim customers = GetCustomers()
    Dim parallelQuery = (From cust In customers.AsParallel().WithExecutionMode(ParallelExecutionMode.ForceParallelism)
                         Where cust.City = "Berlin"
                         Select cust.CustomerName).ToList()
End Sub

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 little work, the query will usually run faster sequentially. Sequential execution is faster because the overhead involved in enabling parallelizing execution is more expensive than the speedup that's 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 expensive and that the query will definitely benefit from parallelization. In such cases, you can use the WithExecutionMode method and specify the ForceParallelism value to instruct PLINQ to always run the query as parallel.

Compiling the Code

Cut and paste this code into the PLINQ Data Sample and call the method from Main.

See also