Parallel Programming Part 2: Waiting For Tasks and Exceptions Handling

Welcome to the second part of the Parallel Programming series that consists of the following part:

In our preceding article and the first part of the entire Parallel Programming series we have learned the key basics of the TPL library and discovered how easy it is to create new tasks that will do the work concurrently. Especially when compared to the old .Net threading model, working with tasks is straightforward and much simpler since the underlying engine takes care of many key aspects for us, so you can easily take advantage of multi-core systems thus make the application faster and more responsive.

In this part, we will take a closer look into two topics that are a little bit advanced, both very important for mastering the TPL. First, we will learn about the options we have for waiting for tasks to complete. Next, we will dive deeper into exception handling that is crucial while working with threads since the application can give various unexpected results when not handled correctly.

Waiting For Tasks

In the previous part of the series, we have used the Task.Result method that stops the execution flow until the given task has completed. However, there are other three methods that allow us to wait for a task that doesn't return any result or for a set of tasks that is useful for achieving some coordination among them.

The following is a brief summary of these additional methods:

  • The Call() method on the Task instance is used to wait until the task has completed. You can optionally set a maximum waiting duration or CancellationToken to enable the task cancellation.

  • The staticTask.WaitForAll() method waits for all the tasks in the supplied task array to complete. Yet again you can add the maximum duration and the cancellation support.

  • The static Task.WaitForAny() waits for the first task of a set of tasks to complete. Setting the duration and cancellation support are optional via the method arguments. 

Waiting For A Single Task To Complete

By calling the instance Wait() method you can wait until a single task has completed. Note that the task is considered to be completed not only when it executes all its workload, but also when it has been cancelled or it has thrown an exception.

There are several overloaded methods available that allow you to add an instance of a CancellationToken to enable the task's cancellation or add some specific waiting time duration in the form of a number of milliseconds or a TimeSpan.

The following example demonstrates the use of the Wait() method. We start by creating a static Workload method that represents the workload. In this case, we will just print the iteration turn to the console and put the task to sleep for 1 second.

  1. static void Workload()  
  2. {  
  3.      for (int i = 0; i < 5; i++)  
  4.      {  
  5.           Console.WriteLine("Task - iteration {0}", i);  
  7.           //sleeping for 1 second  
  8.           Thread.Sleep(1000);  
  9.      }  
  10. }  

We will now create two simple tasks and use Wait() to wait until they have completed. Note that we have used an overloaded version of the method with the second task and restricted it to wait only 2000 milliseconds (2 seconds).

  1. static void Main(string[] args)  
  2. {  
  3.      //creating and starting a simple task  
  4.      Task task = new Task(new Action(Workload));  
  5.      task.Start();  
  7.      //waiting for the task  
  8.      Console.WriteLine("Waiting for task to complete.");  
  9.      task.Wait();  
  10.      Console.WriteLine("Task Completed.");  
  12.      //creating and starting another task             
  13.      task = new Task(new Action(Workload));  
  14.      task.Start();  
  15.      Console.WriteLine("Waiting 2 secs for task to complete.");  
  16.      task.Wait(2000);  
  17.      Console.WriteLine("Wait ended - task completed.");  
  19.      Console.WriteLine("Main method complete. Press any key to finish.");  
  20.      Console.ReadKey();  
  21. }  

                                 Image 1: Waiting for a single task to complete 

Waiting For Several Tasks To Complete

The static Task.WaitAll() method is used to wait for a number of tasks to complete, so it will not return until all the given tasks will either complete, throw an exception or be cancelled. This method uses the same overloading pattern as the Wait() method.

For the sake of demonstration, we have created two tasks and will wait for both until they complete. Note that the second task will print just one line to the console, so it will finish almost immediately. Still, the WaitAll() method won't return until they both have completed. 
  1. static void Main(string[] args)  
  2. {  
  3.      //createing the tasks  
  4.      Task task1 = new Task(() =>  
  5.      {  
  6.           for (int i = 0; i < 5; i++)  
  7.           {  
  8.                Console.WriteLine("Task 1 - iteration {0}", i);  
  10.                //sleeping for 1 second  
  11.                Thread.Sleep(1000);  
  12.           }  
  13.           Console.WriteLine("Task 1 complete");  
  14.      });  
  16.      Task task2 = new Task(() =>  
  17.      {  
  18.           Console.WriteLine("Task 2 complete");  
  19.      });  
  21.      // starting the tasks  
  22.      task1.Start();  
  23.      task2.Start();  
  25.      //waiting for both tasks to complete  
  26.      Console.WriteLine("Waiting for tasks to complete.");  
  27.      Task.WaitAll(task1, task2);  
  28.      Console.WriteLine("Tasks Completed.");  
  30.      Console.WriteLine("Main method complete. Press any key to finish.");  
  31.      Console.ReadKey();  
  32. }  
                                 Image 2: Waiting for several tasks to complete 
Waiting For One Of Many Tasks To Complete

The static Task.WaitAny() method is very similar to the method above (WaitAll), but instead of waiting for all the tasks to complete, it waits only for the first one that either has completed, was cancelled or has thrown an exception. Moreover, it returns the array index of the first completed task.

In the following example, we are starting two tasks and waiting for the first one to finish. Because the workload of the second task is quite simple, it completes first. As a result, the WaitAny() method returns 1 since that is the array index of the first completed task. 
  1. static void Main(string[] args)  
  2. {  
  3.      //creating the tasks  
  4.      Task task1 = new Task(() =>  
  5.      {  
  6.           for (int i = 0; i < 5; i++)  
  7.           {  
  8.                Console.WriteLine("Task 1 - iteration {0}", i);  
  9.                //sleeping for 1 second  
  10.                Thread.Sleep(1000);  
  11.           }  
  12.           Console.WriteLine("Task 1 complete");  
  13.      });  
  15.      Task task2 = new Task(() =>  
  16.      {  
  17.           Console.WriteLine("Task 2 complete");  
  18.      });  
  20.      //starting the tasks  
  21.      task1.Start();  
  22.      task2.Start();  
  24.      //waiting for the first task to complete  
  25.      Console.WriteLine("Waiting for tasks to complete.");  
  26.      int taskIndex = Task.WaitAny(task1, task2);  
  27.      Console.WriteLine("Task Completed - array index: {0}", taskIndex);  
  29.      Console.WriteLine("Main method complete. Press any key to finish.");  
  30.      Console.ReadKey();  
  31. }  
                                Image 3: Waiting for one of many tasks to complete 

Note: When the WaitAny() method returns, all the other started tasks will continue executing.

Exceptions Handling In Tasks

No matter whether you write just a sequential application or add in some concurrency, you still must handle exceptions. Otherwise, the application will crash when an exception is thrown, leaving a poor use experience behind. In parallel programming, it is even more important since the application could behave unpredictably. Thankfully, TPL provides a consistent model for handling exceptions that are thrown during a task's execution.

When an exception occurs within a task (and is not caught), it is not thrown immediately. Instead, it is squirreled away by the .Net framework and thrown when some trigger member method is called, such as Task.Result, Task.Wait(), Task.WaitAll() or Task.WaitAny(). In this case, an instance of System.AggregateException is thrown that acts as a wrapper around one or more exceptions that have occurred. This is important for methods that coordinate multiple tasks like Task.WaitAll() and Task.WaitAny(), so the AggregateException is able to wrap all the exceptions within the running tasks that have occurred.

In the following example, we are creating and starting three tasks, two of which throw different exceptions. After starting these tasks, the main calling thread calls the WaitAll() method and catches the AggregateException. Finally, it iterates through the InnerExceptions property and prints out the details regarding the thrown exceptions. This property is the wrapper holding all the information about the aggregated exceptions.

  1. static void Main(string[] args)  
  2. {  
  3.      //creating the tasks  
  4.      Task task1 = new Task(() =>  
  5.      {  
  6.           NullReferenceException exception = new NullReferenceException();  
  7.           exception.Source = "task1";  
  8.           throw exception;  
  9.      });  
  11.      Task task2 = new Task(() =>  
  12.      {  
  13.           throw new IndexOutOfRangeException();  
  14.      });  
  16.      Task task3 = new Task(() =>  
  17.      {  
  18.           Console.WriteLine("Task 3");  
  19.      });  
  21.      //starting the tasks  
  22.      task1.Start();   
  23.      task2.Start();   
  24.      task3.Start();  
  26.      //waiting for all the tasks to complete              
  27.      try  
  28.      {  
  29.           Task.WaitAll(task1, task2, task3);  
  30.      }  
  31.      catch (AggregateException ex)  
  32.      {  
  33.           //enumerate the exceptions  
  34.           foreach (Exception inner in ex.InnerExceptions)  
  35.           {  
  36.                Console.WriteLine("Exception type {0} from {1}", inner.GetType(), inner.Source);  
  37.           }  
  38.      }  
  40.      Console.WriteLine("Main method complete. Press any key to finish.");  
  41.      Console.ReadKey();  
  42. }  
                                          Image 4: Exceptions handling in tasks 

In order to coordinate tasks, we use the instance method Wait() or one from the two static methods WaitAll()/WaitAny(). These methods allow the application either to wait until all the given tasks have completed or wait until any of the tasks completes first.

An exception that occurs during a task execution is not thrown until some trigger member is called. We use and handle the AggregateException that aggregates all the tasks exceptions that have been thrown.

In the next part of the series, we will take a closer look at tasks synchronization, discover synchronization primitives and learn how to share data among several running tasks properly to avoid deadlocks and data races.