Udostępnij za pośrednictwem


How to: Combine Parallel and Sequential LINQ Queries

This example shows how to use the AsSequential<TSource> 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.

Caution noteCaution

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

The following example shows one scenario in which AsSequential<TSource> is required, namely to preserve the ordering that was established in a previous clause of the query.

' 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
// 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);
}

Compiling the Code

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

Concepts

Parallel LINQ (PLINQ)