Home > Article > Backend Development > How to run multiple asynchronous tasks in C# and wait for them all to complete?
Task.WaitAll blocks the current thread until all other tasks have completed execution.
Task.WhenAll method is used to create a task that will complete if and only if all other tasks have completed. In the first example, we can see that when using Task.WhenAll, task completion occurs before other tasks complete. This means that Task.WhenAll will not block execution. In the second example, we can see that when using Task.WaitAll, task completion is only executed after all other tasks have completed. This means that Task.WaitAll blocks execution.
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(); }
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
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(); }
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
The above is the detailed content of How to run multiple asynchronous tasks in C# and wait for them all to complete?. For more information, please follow other related articles on the PHP Chinese website!