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中文網其他相關文章!