如何:在 PLINQ 中指定執行模式How to: Specify the Execution Mode in PLINQ

這個範例示範如何強制 PLINQ 略過其預設啟發學習法並以平行方式處理查詢,而不考慮查詢的種類。This example shows how to force PLINQ to bypass its default heuristics and parallelize a query regardless of the query's shape.

警告

這個範例是為了示範用法,執行速度可能比不上對應的循序 LINQ to Objects 查詢。This example is intended to demonstrate usage, and might not run faster than the equivalent sequential LINQ to Objects query. 如需加速的詳細資訊,請參閱認識 PLINQ 中的加速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 的設計,是要利用可以平行處理的機會。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. 因此,PLINQ 不會自動平行處理每個查詢。Therefore, PLINQ does not automatically parallelize every query. 它會先檢查查詢的種類,和組成查詢的各個運算子。It first examines the shape of the query and the various operators that comprise it. 根據這項分析,預設執行模式的 PLINQ 就能決定要循序執行部分或所有的查詢。Based on this analysis, PLINQ in the default execution mode may decide to execute some or all of the query sequentially. 不過,在某些情況下,您所能得知的查詢資訊,不僅僅是 PLINQ 能夠從其分析中判斷的資訊。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. 在這種情況下,您可以使用 WithExecutionMode方法並指定 ForceParallelism 值,指示 PLINQ 永遠以平行方式執行查詢。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

將此程式碼剪下並貼到 PLINQ 資料範例,並從 Main 呼叫此方法。Cut and paste this code into the PLINQ Data Sample and call the method from Main.

請參閱See also