Parallel,LINQ,c#

Kerim 8/7/2016 0

Parallel LINQ

C#
Parallel LINQ (PLINQ) is to LINQ to Objects what parallel loops are to ordinary loops. PLINQ executes LINQ queries, but distributes the evaluation of the user delegates over multiple threads. To opt into PLINQ, use the AsParallel() extension method:

            arr.AsParallel().Where(x => ExpensiveFilter(x));
             foreach (var x in q)
            {
                Console.WriteLine(x);
            }
 
DO use PLINQ to express computations with an expensive operation applied over a sequence. 
BE AWARE that by default, PLINQ does not preserve ordering of elements in a query. For example, the results of this query will be printed in an unspecified order:

            var q = Enumerable .Range(0, 100).AsParallel()
                .Select(x => -x);
           
            foreach (var x in q)
                 Console.WriteLine(x); 
To turn on ordering, you can either use the AsOrdered() operator to preserve the initial ordering in the input sequence, or use OrderBy() to sort the values.
Here is a version of the code sample above that preserves the ordering of the input elements, and prints the corresponding outputs in the correct order:

            var q = Enumerable .Range(0, 100)
                .AsParallel().AsOrdered().Select(x => -x);
           
            foreach (var x in q)
                 Console.WriteLine(x);

DO keep PLINQ queries simple to make them easy to reason about. If possible, break up more complex queries so that the cheap but complex part is done externally to PLINQ, e.g. in LINQ to Objects. Consider this example:

            var q = Enumerable .Range(0, 100)
                .TakeWhile(x => SomeFunction(x)).AsParallel()
                .Select(x => Foo(x));
           
            foreach (var x in q)
                 Console.WriteLine(x);

Notice that the AsParallel() is placed after the TakeWhile() operator rather than immediately on the data source.

To use on-demand load-balancing partitioning, use Partitioner.Create() method, passing in the true value for the loadBalancing parameter:

            int[] input = { 1, 2, 3, 4, 54, 6, 7, 98 };
            Partitioner<int > partitioner = Partitioner.Create(input, true);
            var q = partitioner
                .AsParallel()
                .Select(x =>
                Foo(x)).ToArray();
 

Report Bug

Please Login to Report Bug

Reported Bugs

Comments

Please Login to Comment

Comments