How to: Combine Parallel and Sequential LINQ Queries

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 often slower than parallel, sometimes it's necessary to produce correct results.

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

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 order in orders.AsParallel()
                 orderby order.OrderID
                 select new
                 {
                     order.OrderID,
                     OrderedOn = order.OrderDate,
                     ShippedOn = order.ShippedDate
                 })
                 .AsSequential().Take(5);
}
' Paste into PLINQDataSample class
Shared Sub SequentialDemo()

    Dim orders = GetOrders()
    Dim query = From ord In orders.AsParallel()
                Order By ord.OrderID
                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

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