如何在 C# 中运行多个异步任务并等待它们全部完成?
Task.WaitAll 方法会阻塞当前线程,直到所有其他任务都执行完成。
Task.WhenAll 方法用于创建一个任务,只有当所有其他任务都完成后,此任务才会完成。在第一个示例中,我们可以看到,当使用 Task.WhenAll 时,任务完成的执行先于其他任务的完成。这意味着 Task.WhenAll 不会阻塞执行。在第二个示例中,我们可以看到,当使用 Task.WaitAll 时,任务完成的执行仅在所有其他任务完成后才会执行。这意味着 Task.WaitAll 会阻塞执行。
示例
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
广告