I have a foreach
loop that I am parallelizing and I noticed something odd. The code looks like
double sum = 0.0;
Parallel.ForEach(myCollection
it is possible that the sum variable is being unexpectantly affected by the parallelization?
Yes.
Access to a double
is not atomic and the sum += ...
operation is never thread-safe, not even for types that are atomic. So you have multiple race conditions and the result is unpredictable.
You could use something like:
double sum = myCollection.AsParallel().Sum(arg => ComplicatedFunction(arg));
or, in a shorter notation
double sum = myCollection.AsParallel().Sum(ComplicatedFunction);