When I run the code below the result is always different when it comes to the 5th and 6th digit:
public void TestParallel()
{
object locker = new object();
double grandTotal = 0;
Parallel.For( 1, 1000000,
() => 0.0, // Initialize the local value.
( i, state, localTotal ) => // Body delegate. Notice that it
{
return localTotal + Math.Sqrt( i ); // returns the new local total.
},
localTotal => // Add the local value
{
lock( locker ) grandTotal += localTotal; // to the master value.
}
);
Console.WriteLine( string.Format( "Grand Total = {0}", grandTotal ) );
}
I have no clue why the result is not always Grand Total = 666666166,458842. This is what i get when running it like this:
double grandTotal = 0;
for ( int i = 1; i < 1000000; i++ )
{
grandTotal += Math.Sqrt( i ); // returns the new local total.
}
Console.WriteLine( string.Format( "Grand Total = {0}", grandTotal ) );