I have following scenario ,
Parallel.Foreach(al , sentence =>
{
function abc
{
double x;
}
y = Add(ref y, x)
}
public static double Add(ref double location1, double value)
{
double newCurrentValue = 0;
while (true)
{
double currentValue = newCurrentValue;
double newValue = currentValue + value;
newCurrentValue = Interlocked.CompareExchange(ref location1, newValue, currentValue);
if (newCurrentValue == currentValue)
return newValue;
}
}
for each sentence in array of sentence al there is some value of x that will be calculated. And I want to sum up these values of all sentences in to variable y. But when I run code each time I get different value of y. And I guess its because x is getting overwritten before writing into y. So for each sentence is Parallel Foreach creating different or same copy of function abc? How can I fix this.