This documentation is archived and is not being maintained.

How to: Specify Merge Options in PLINQ

This example shows how to specify the merge options that will apply to all subsequent operators in a PLINQ query. You do not have to set merge options explicitly, but doing so may improve performance. For more information about merge options, see Merge Options in PLINQ.

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 demonstrates the behavior of merge options in a basic scenario that has an unordered source and applies an expensive function to every element.

Class MergeOptions2

    Sub DoMergeOptions()

        Dim nums = Enumerable.Range(1, 10000)

        ' Replace NotBuffered with AutoBuffered 
        ' or FullyBuffered to compare behavior.
        Dim scanLines = From n In nums.AsParallel().WithMergeOptions(ParallelMergeOptions.NotBuffered)
              Where n Mod 2 = 0
              Select ExpensiveFunc(n)

        Dim sw = System.Diagnostics.Stopwatch.StartNew()
        For Each line In scanLines

        Console.WriteLine("Elapsed time: {0} ms. Press any key to exit.")

    End Sub
    ' A function that demonstrates what a fly
    ' sees when it watches television :-)
    Function ExpensiveFunc(ByVal i As Integer) As String
        Return String.Format("{0} *****************************************", i)
    End Function
End Class

In cases where the AutoBuffered option incurs an undesirable latency before the first element is yielded, try the NotBuffered option to yield result elements faster and more smoothly.