Skip to content

Instantly share code, notes, and snippets.

@angelovstanton
Created August 23, 2015 13:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save angelovstanton/03cc00bd0c5fc031fe17 to your computer and use it in GitHub Desktop.
Save angelovstanton/03cc00bd0c5fc031fe17 to your computer and use it in GitHub Desktop.
int[] nums = Enumerable.Range(0, 1000000).ToArray();
long total = 0;
Parallel.ForEach<int, long>(nums, // source collection
() => 0, // method to initialize the local variable
(j, loop, subtotal) => // method invoked by the loop on each iteration
{
subtotal += j; //modify local variable
return subtotal; // value to be passed to next iteration
},
// Method to be executed when each partition has completed.
// finalResult is the final value of subtotal for a particular partition.
(finalResult) => Interlocked.Add(ref total, finalResult));
Console.WriteLine("The total from Parallel.ForEach is {0:N0}", total);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment