Export (0) Print
Expand All

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.

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.
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);
}


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.

Community Additions

ADD
Show:
© 2014 Microsoft