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

1

5

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 ??
}
Bronchiectasis answered 26/5, 2015 at 23:57 Comment(0)
S
7

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.

Sulfanilamide answered 27/5, 2015 at 0:4 Comment(2)
Even if I modify the body of the lambda to set the Bar property to another value, that value doesn't stick either. I'm still a bit perplexed; I'm under the assumption that ForAll() is iterating over the actual list. In other words, why would the lambda not be ref?Bronchiectasis
Now that I think about it, this doesn't even have anything to do with PLINQ...it's the same behavior with .ForEach().Bronchiectasis

© 2022 - 2024 — McMap. All rights reserved.