Parallel For Loop : Break Or Stop

In my last post I had discussed about Parallel For loops and in what situation it can be useful compared to a sequential loop.In this post we will take a look at how to break or exit from a Parallel For loop.We can use the break or exit keywords for this purpose as Parallel For loop is not programming language construct but a method of the System.Threading.Tasks.Parallel class.To break or exit we need to use any one of the following overloads of Parallel.For method:

  • public static ParallelLoopResult For(int fromInclusive,int toExclusive,Action<int, ParallelLoopState> body)
  • public static ParallelLoopResult For(long fromInclusive,long toExclusive,Action<long, ParallelLoopState> body)
  • public static ParallelLoopResult For(int fromInclusive,int toExclusive,ParallelOptions parallelOptions,Action<int, ParallelLoopState> body)
  • public static ParallelLoopResult For(long fromInclusive,long toExclusive,ParallelOptions parallelOptions,Action<long, ParallelLoopState> body)

The key here is the ParallelLoopState that is passed as input to the Action delegate.ParallelLoopState class has two methods:

  • Break – This method notifies that all iterations higher than the iteration from which Break is called will be stopped however the lower iterations will be still completed.
  • Stop – This method notifies that all the iterations will be stopped.

Let’s consider the following code sample:

static void Main(string[] args)
{
    List<int> list = new List<int>(); 

    Console.WriteLine("Loop Start");
    Parallel.For(0, 10000, (i, loopState) =>
        {
            if (i == 850)
            {
                loopState.Break();
            } 

            list.Add(i);
        }
    );
    Console.WriteLine("Loop End");
    foreach (int i in list)
    {
        Console.WriteLine(i);
    }
    Console.Read();
}

Here the output will show that last entry in the loop is always 850 or less.This is because Break is called at iteration 850 no iteration higher than 850 is executed but lower than 850 are still completed.

Now let’s tweak the above code a bit and use it for Stop as shown below:

static void Main(string[] args)
      {
          List<int> list = new List<int>(); 

          Console.WriteLine("Loop Start");
          Parallel.For(0, 10000, (i, loopState) =>
              {
                  if (i == 850)
                  {
                      loopState.Stop();
                  } 

                  list.Add(i);
              }
          );
          Console.WriteLine("Loop End");
          foreach (int i in list)
          {
              Console.WriteLine(i);
          }
          Console.Read();
      }

Here in some of the runs you might see that last entry in List<int> is higher than 850.

However after Stop or Break is called there might be some of the threads still running for sometime.Here we can use the IsStopped property of ParallelLoopState class to check if the loop is stopped by some other iteration.

That’s all for now.In the next post we will take a look at exception handling in Parallel For loops.

This entry was posted in Framework & Libraries. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *