CSharp Parallel Programming

Last Updated: 3/11/2022

ParallelLoopState

Enables iterations of parallel loops to interact with other iterations. An instance of this class is provided by the Parallel class to each loop;

Break

Communicates that the Parallel loop should cease execution of iterations beyond the current iteration at the system's earliest convenience.

var rnd = new Random();
int breakIndex = rnd.Next(1, 10);

Parallel.For(1, 100, (i, state) => {
	Console.WriteLine("Beginning iteration {0}", i);
	
	int delay;
	lock(rnd)
	{
		delay = rnd.Next(1, 1000);
	}
	Thread.Sleep(delay);
	
	if(i == breakIndex) 
	{
		Console.WriteLine("Break in iteration {0}", i);
		state.Break();
		return;
	}
	
	if(state.ShouldExitCurrentIteration)
	{
		if(i > state.LowestBreakIteration)
			return;
	}
	Console.WriteLine("Completed iteration {0}", i);
});
  • Break indicates that no iterations after the current iteration should be run. It effectively cancels any additional iterations of the loop.
  • Break sets the LowestBreakIteration property to the current iteration's index
  • It does not stop any iterations that have already begun execution. You can check ShouldExitCurrentIteration and exit from the iteration if its index is greater than the LowestBreakIteration property value.

Stop

Communicates that the Parallel loop should cease execution at the system's earliest convenience.

var rnd = new Random();
int stopIndex = rnd.Next(1, 10);

Parallel.For(1, 100, (i, state) => {
	Console.WriteLine("Beginning iteration {0}", i);
	
	int delay;
	Monitor.Enter(rnd);
	delay = rnd.Next(1, 1000);
	Monitor.Exit(rnd);
	Thread.Sleep(delay);
	
	if(i == stopIndex) 
	{
		Console.WriteLine("Stop in iteration {0}", i);
		state.Stop();
		return;
	}
	
	if(state.IsStopped)
	{
		return;
	}
	Console.WriteLine("Completed iteration {0}", i);
});
  • Calling the Stop method indicates that any iterations of the loop that have not yet started need not be run.
  • It does not stop any iterations that have already begun execution. You can check IsStopped property and exit.

Example