Skip to content

Instantly share code, notes, and snippets.

@leandrosilva
Last active November 8, 2021 21:21
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 leandrosilva/d14e14b86b756d42ff67bb3e31b78cd1 to your computer and use it in GitHub Desktop.
Save leandrosilva/d14e14b86b756d42ff67bb3e31b78cd1 to your computer and use it in GitHub Desktop.
Source code for the article "Tudo ao mesmo tempo agora com C#" originally published at https://medium.com/pricefy-labs
private static void ParallelInvoke()
{
var numberOfIterations = 1000;
var min = 0;
var max = 100_000_000;
Console.WriteLine($"Generating random numbers from {min} to {max} over {numberOfIterations} iterations");
var nums = GenerateRandomNumbers(numberOfIterations, min, max).Select(num => (long)num).ToArray();
// With Parallel LINQ it is a piece of cake -- fast as f*k
var originalSum = nums.AsParallel().Sum();
Parallel.Invoke(
() => ExpensivePlusOne(ref nums, 0, nums.Length / 2),
() => ExpensiveMinusTwo(ref nums, nums.Length / 2, nums.Length)
);
var newSum = nums.AsParallel().Sum();
Console.WriteLine($"Sum of all random generated numbers are {originalSum} (original) and {newSum} (new) [{originalSum - newSum} less]");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment