-
-
Save leandrosilva/bb4b11c92e9ac37c7e0882ea65251d2e 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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static void ParallelParentAndChildren() | |
{ | |
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(); | |
var task = Task.Factory.StartNew( | |
() => ProcessNumbers(nums), // <-- let's pretend it is a so freaking CPU-intensive method | |
CancellationToken.None, | |
TaskCreationOptions.None, | |
TaskScheduler.Default | |
); | |
Console.WriteLine("Spawned parallel process of numbers and will wait until completion"); | |
task.Wait(); | |
Console.WriteLine("Parallel process of numbers has completed"); | |
} | |
private static void ProcessNumbers(long[] nums) | |
{ | |
var odds = new ConcurrentBag<long>(); | |
var evens = new ConcurrentBag<long>(); | |
Console.WriteLine("Will divide odds / evens in parallel"); | |
Parallel.ForEach(nums, (num) => | |
{ | |
if (num % 2 != 0) | |
odds.Add(num); | |
else | |
evens.Add(num); | |
}); | |
Task.Factory.StartNew( | |
() => ExpensiveWorkWithOdds(odds.ToArray()), | |
CancellationToken.None, | |
TaskCreationOptions.AttachedToParent, // <-- pay attention at here | |
TaskScheduler.Default | |
); | |
Console.WriteLine("Spawned parallel expensive work on odds"); | |
Task.Factory.StartNew( | |
() => ExpensiveWorkWithEvens(evens.ToArray()), | |
CancellationToken.None, | |
TaskCreationOptions.AttachedToParent, // <-- pay attention at here | |
TaskScheduler.Default | |
); | |
Console.WriteLine("Spawned parallel expensive work on evens"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment