How to run multiple async tasks and waiting for them all to complete in C#?


The Task.WaitAll blocks the current thread until all other tasks have completed execution.

The Task.WhenAll method is used to create a task that will complete if and only if all the other tasks have complete. In the 1st example, we could see that when using Task.WhenAll the task complete is executed before the other tasks are completed. This means that Task.WhenAll doesn’t block the execution. And in the 2nd example, we could see that when using Task.WaitAll the task complete is executed only after all the other tasks are completed. This means that Task.WaitAll block the execution.

Example

static void Main(string[] args){
   Task task1 = new Task(() =>{
      for (var i = 0; i < 5; i++){
         Console.WriteLine("Task 1 - iteration {0}", i);
         Task.Delay(1000);
      }
      Console.WriteLine("Task 1 complete");
   });
   Task task2 = new Task(() =>{
      for (var i = 0; i < 5; i++){
         Console.WriteLine("Task 2 - iteration {0}", i);
         Task.Delay(1000);
      }
      Console.WriteLine("Task 2 complete");
   });
   task1.Start();
   task2.Start();
   Console.WriteLine("Waiting for tasks to complete.");
   Task.WhenAll(task1, task2);
   Console.WriteLine("Both Tasks Completed.");
   Console.ReadLine();
}

Output

Waiting for tasks to complete.
Both Tasks Completed.
Task 1 - iteration 0
Task 2 - iteration 0
Task 2 - iteration 1
Task 2 - iteration 2
Task 2 - iteration 3
Task 1 - iteration 1
Task 1 - iteration 2
Task 1 - iteration 3
Task 1 - iteration 4
Task 1 complete
Task 2 - iteration 4
Task 2 complete

Example

static void Main(string[] args){
   Task task1 = new Task(() =>{
      for (var i = 0; i < 5; i++){
         Console.WriteLine("Task 1 - iteration {0}", i);
         Task.Delay(1000);
      }
      Console.WriteLine("Task 1 complete");
   });
   Task task2 = new Task(() =>{
      for (var i = 0; i < 5; i++){
         Console.WriteLine("Task 2 - iteration {0}", i);
         Task.Delay(1000);
      }
      Console.WriteLine("Task 2 complete");
   });
   task1.Start();
   task2.Start();
   Console.WriteLine("Waiting for tasks to complete.");
   Task.WaitAll(task1, task2);
   Console.WriteLine("Both Tasks Completed.");
   Console.ReadLine();
}

Output

Waiting for tasks to complete.
Task 1 - iteration 0
Task 2 - iteration 0
Task 1 - iteration 1
Task 1 - iteration 2
Task 1 - iteration 3
Task 1 - iteration 4
Task 1 complete
Task 2 - iteration 1
Task 2 - iteration 2
Task 2 - iteration 3
Task 2 - iteration 4
Task 2 complete
Both Tasks Completed

Updated on: 05-Dec-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements