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
以上是如何在 C# 中运行多个异步任务并等待它们全部完成?的详细内容。更多信息请关注PHP中文网其他相关文章!