Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parallel LINQ - .Select() + .ForAll() returning bizarre results

Tags:

c#

plinq

For the life of me, I can't figure out why all the foos are not null. I'm assuming the .ForAll() should be executing before I call the .All() method, but it's not?

public class Foo
{
    public string Bar { get; set; }
}

static void Main(string[] args)
{
    var foos = new List<Foo> { new Foo(), new Foo(), new Foo() };
    var newFoos = foos
        .AsParallel()
        .Select(x =>
        {
            x.Bar = "";
            return x;
        });
    newFoos.ForAll(x => x = null);
    var allFoosAreNull = newFoos.All(x => x == null);
    Console.WriteLine(allFoosAreNull); // False ??
}
like image 685
Brad M Avatar asked May 26 '15 23:05

Brad M


People also ask

Does LINQ Select run in parallel?

LINQ to Objects and LINQ to XML queries are designed to work sequentially, and do not involve multi-threading, concurrency, or parallel computing.

Which extension method do you need to run a parallel query in PLINQ?

AsParallel extension method on the source sequence and executing the query by using the ParallelEnumerable. ForAll method. This documentation uses lambda expressions to define delegates in PLINQ. If you are not familiar with lambda expressions in C# or Visual Basic, see Lambda Expressions in PLINQ and TPL.

What is AsParallel in Linq C#?

AsParallel(IEnumerable)Enables parallelization of a query. public: [System::Runtime::CompilerServices::Extension] static System::Linq::ParallelQuery ^ AsParallel(System::Collections::IEnumerable ^ source); C# Copy.

What is parallel LINQ?

Parallel LINQ (PLINQ) is a parallel implementation of the Language-Integrated Query (LINQ) pattern. PLINQ implements the full set of LINQ standard query operators as extension methods for the System. Linq namespace and has additional operators for parallel operations.


1 Answers

When you do this

newFoos.ForAll(x => x = null);

you are assigning null to x, which is the parameter of your lambda. x is local to the lambda. It is not a ref parameter, and assigning values to it has no effect outside of its body. Effectively, that line does nothing.

like image 149
recursive Avatar answered Oct 10 '22 15:10

recursive