如何:結合平行和循序 LINQ 查詢How to: Combine Parallel and Sequential LINQ Queries

此範例示範如何使用 AsSequential 方法來指示 PLINQ 循序處理查詢中所有後續的運算子。This example shows how to use the AsSequential method to instruct PLINQ to process all subsequent operators in the query sequentially. 雖然循序處理的速度通常比平行處理慢,但有時為了產生正確結果卻是必要的。Although sequential processing is generally slower than parallel, sometimes it is necessary to produce correct results.

警告

這個範例是為了示範用法,執行速度可能比不上對應的循序 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

下列範例示範必須使用 AsSequential 的案例,也就是要保留先前的查詢子句中所建立的順序。The following example shows one scenario in which AsSequential is required, namely to preserve the ordering that was established in a previous clause of the query.

// Paste into PLINQDataSample class.
static void SequentialDemo()
{
    var orders = GetOrders();
    var query = (from ord in orders.AsParallel()
                 orderby ord.CustomerID
                 select new
                 {
                     Details = ord.OrderID,
                     Date = ord.OrderDate,
                     Shipped = ord.ShippedDate
                 }).
                        AsSequential().Take(5);
}
' Paste into PLINQDataSample class
Shared Sub SequentialDemo()

    Dim orders = GetOrders()
    Dim query = From ord In orders.AsParallel()
                 Order By ord.CustomerID
                 Select New With
                 {
                     ord.OrderID,
                     ord.OrderDate,
                     ord.ShippedDate
                 }

    Dim query2 = query.AsSequential().Take(5)

    For Each item In query2
        Console.WriteLine("{0}, {1}, {2}", item.OrderDate, item.OrderID, item.ShippedDate)
    Next
End Sub

編譯程式碼Compiling the Code

若要編譯及執行此程式碼,請將它貼入 PLINQ 資料範例專案,加入從 Main 呼叫方法一行,然後按 F5 鍵。To compile and run this code, paste it into the PLINQ Data Sample project, add a line to call the method from Main, and press F5.

請參閱See also