Skip to content

Instantly share code, notes, and snippets.

@leandrosilva
Last active November 8, 2021 21:20
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/5814047639dbb843da73610b305583a9 to your computer and use it in GitHub Desktop.
Save leandrosilva/5814047639dbb843da73610b305583a9 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 ParallelFor()
{
var numberOfIterations = 1000;
var min = 0;
var max = 100_000_000;
var random = new Random();
var breakIndex = random.Next(1, numberOfIterations);
Console.WriteLine($"Generating random numbers from {min} to {max} over {numberOfIterations} iterations");
Console.WriteLine($"Random break index: {breakIndex}");
var result = Parallel.For(1, numberOfIterations, (i, state) =>
{
Console.WriteLine($"- Iteration #{i} > Begin at thread #{Thread.CurrentThread.ManagedThreadId}, task #{Task.CurrentId}");
// Has .Break() been called by another parallel iteration?
if (state.ShouldExitCurrentIteration)
{
// Is this current iteration greater then the one where .Break() was invoked?
if (state.LowestBreakIteration < i)
{
Console.WriteLine($"- Iteration #{i} > Will exit now <-----------");
return;
}
}
int num;
// A naive lock for educative purpose only
lock (random)
{
num = random.Next(min, max);
}
// If it got to the break index, invokes .Break() to prevent further iterations
if (i == breakIndex)
{
Console.WriteLine($"- Iteration #{i} > Got to break index <-----------");
state.Break();
}
Console.WriteLine($"- Iteration #{i} > End: {num}");
});
if (result.LowestBreakIteration.HasValue)
Console.WriteLine($"Lowest break iteration? {result.LowestBreakIteration}");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment