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);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…