Parallel.For(): Update variable outside of loop

Posted by TSS on Stack Overflow See other posts from Stack Overflow or by TSS
Published on 2010-05-05T14:37:54Z Indexed on 2010/05/06 12:08 UTC
Read the original article Hit count: 132

Filed under:
|
|
|

I'm just looking in to the new .NET 4.0 features. With that, I'm attempting a simple calculation using Parallel.For and a normal for(x;x;x) loop.

However, I'm getting different results about 50% of the time.

long sum = 0;

Parallel.For(1, 10000, y =>
    {
        sum += y;
    }
);

Console.WriteLine(sum.ToString());

sum = 0;

for (int y = 1; y < 10000; y++)
{
   sum += y;
}
Console.WriteLine(sum.ToString());

My guess is that the threads are trying to update "sum" at the same time.
Is there an obvious way around it?

© Stack Overflow or respective owner

Related posts about .net-4.0

Related posts about c#