BobSwanson BobSwanson - 1 month ago 22
C# Question

Parallel.ForEach does not update shared variable

Having the folloing code, how can I update shared variable?

List<Person> list = new List<Person> {new Person {Age = 1}, new Person {Age = 2}, new Person {Age = 5}};
long total = 0;

Parallel.ForEach(list, () => 0, (person, loop, subtotal) =>
{
Add(person, subtotal);
return subtotal;
},

finalResult => Interlocked.Add(ref total, finalResult)
);

public static void Add(Person person, int shared)
{
// Do some work
shared =+ person.Age;
}


For some reason shared comes back as 0.

Answer

Shared comes back as 0, because it was sent in as 0 and was passed by value. You need to use the ref keyword, or address this behavior in some other way(static variable).

public static void Add(Person person, ref int shared)
{
    // Do some work
    shared =+ person.Age;
}

It looks like you also have an issue where you're using '= +' in place of '+='.

public static void Add(Person person, ref int shared)
{
    // You likely meant to do this.
    shared += person.Age;
}
Comments