Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Source code for the article "Tudo ao mesmo tempo agora com C#" originally published at
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 <-----------");
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 <-----------");
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