• Controlling Parallelization

    This article assumes that Parallel LINQ (PLINQ) will always do the right thing: choosing whether or not to run in parallel, for instance, and deciding how to distribute the components of a query over multiple threads. However, you can take control of PLINQ to force it to bend to your will by using the With* extensions.

    If, when using the debugging tools described in this article, you notice that PLINQ is not processing a query in parallel, you can force it to do so by passing the ParallelExecutionMode. ForceParallelism value to the WithExecutionMode method:

    ords = From o In le.Orders.AsParallel.
    WithExecutionMode(ParallelExecutionMode.ForceParallelism)

    If you want to specify the number of threads to use (for instance, to try to ensure that one or more cores are left free) you can use the WithDegreeOfParallelism method. This example limits, or forces, the number of threads to three:

    ords = From o In le.Orders.AsParallel.
    WithDegreeOfParallelism(3)

    You can also terminate processing by using cancellation. You first create a CancellationTokenSource object and pass it to the WithCancellation extension:

    Dim ctx As New System.Threading.CancellationTokenSource
    ords = From o In le.Orders.AsParallel.
    WithCancellation(ctx.Token)
    Where o.RequiredDate > Now
    Select o

    For Each ord As Order In ords
    totFreight += ord.Freight
    If totFreight > FreightChargeLimit Then
    ctx.Cancel()
    End If
    Next

    If you’re processing the results of a PLINQ query in a For...Each loop, exiting the loop automatically invokes cancellation.


0 comments:

Leave a Reply