Task.WhenAll 方法

定義

建立當所有提供的工作完成時才會完成的工作。

多載

WhenAll(IEnumerable<Task>)

建立一個工作,當可列舉集合中的所有 Task 物件完成時,會完成此工作。

WhenAll(Task[])

建立一個工作,當陣列中的所有 Task 物件完成時,會完成此工作。

WhenAll<TResult>(IEnumerable<Task<TResult>>)

建立一個工作,當可列舉集合中的所有 Task<TResult> 物件完成時,會完成此工作。

WhenAll<TResult>(Task<TResult>[])

建立一個工作,當陣列中的所有 Task<TResult> 物件完成時,會完成此工作。

WhenAll(IEnumerable<Task>)

建立一個工作,當可列舉集合中的所有 Task 物件完成時,會完成此工作。

public:
 static System::Threading::Tasks::Task ^ WhenAll(System::Collections::Generic::IEnumerable<System::Threading::Tasks::Task ^> ^ tasks);
public static System.Threading.Tasks.Task WhenAll (System.Collections.Generic.IEnumerable<System.Threading.Tasks.Task> tasks);
static member WhenAll : seq<System.Threading.Tasks.Task> -> System.Threading.Tasks.Task
Public Shared Function WhenAll (tasks As IEnumerable(Of Task)) As Task

參數

tasks
IEnumerable<Task>

要等待完成的工作。

傳回

Task

工作,代表所有提供的工作已完成。

例外狀況

tasks 引數以前是 null

tasks集合包含 null 工作。

範例

下列範例會建立一組工作,以偵測陣列中的 URL。 工作會儲存在 List<Task> 傳遞至 方法的集合中 WhenAll(IEnumerable<Task>) 。 呼叫 Wait 方法可確保所有線程都已完成之後,此範例會 Task.Status 檢查 屬性,以判斷是否有任何工作發生錯誤。

using System;
using System.Collections.Generic;
using System.Net.NetworkInformation;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      int failed = 0;
      var tasks = new List<Task>();
      String[] urls = { "www.adatum.com", "www.cohovineyard.com",
                        "www.cohowinery.com", "www.northwindtraders.com",
                        "www.contoso.com" };
      
      foreach (var value in urls) {
         var url = value;
         tasks.Add(Task.Run( () => { var png = new Ping();
                                     try {
                                        var reply = png.Send(url);
                                        if (! (reply.Status == IPStatus.Success)) {
                                           Interlocked.Increment(ref failed);
                                           throw new TimeoutException("Unable to reach " + url + ".");
                                        }
                                     }
                                     catch (PingException) {
                                        Interlocked.Increment(ref failed);
                                        throw;
                                     }
                                   }));
      }
      Task t = Task.WhenAll(tasks);
      try {
         t.Wait();
      }
      catch {}   

      if (t.Status == TaskStatus.RanToCompletion)
         Console.WriteLine("All ping attempts succeeded.");
      else if (t.Status == TaskStatus.Faulted)
         Console.WriteLine("{0} ping attempts failed", failed);      
   }
}
// The example displays output like the following:
//       5 ping attempts failed
Imports System.Collections.Generic
Imports System.Net.NetworkInformation
Imports System.Threading
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Dim failed As Integer = 0
      Dim tasks As New List(Of Task)()
      Dim urls() As String = { "www.adatum.com", "www.cohovineyard.com",
                              "www.cohowinery.com", "www.northwindtraders.com",
                              "www.contoso.com" }
      
      For Each value In urls
         Dim url As String = value
         tasks.Add(Task.Run( Sub()
                                Dim png As New Ping()
                                Try
                                   Dim reply = png.Send(url)
                                   If Not reply.Status = IPStatus.Success Then
                                      Interlocked.Increment(failed)
                                      Throw New TimeoutException("Unable to reach " + url + ".")
                                   End If
                                   Catch e As PingException
                                      Interlocked.Increment(failed)
                                      Throw
                                   End Try
                             End Sub))
      Next
      Dim t As Task = Task.WhenAll(tasks)
      Try
         t.Wait()
      Catch
      End Try   

      If t.Status = TaskStatus.RanToCompletion
         Console.WriteLine("All ping attempts succeeded.")
      ElseIf t.Status = TaskStatus.Faulted
         Console.WriteLine("{0} ping attempts failed", failed)      
      End If
   End Sub
End Module
' The example displays output like the following:
'     5 ping attempts failed

備註

當您對一組工作的狀態或一組工作擲回的例外狀況感興趣時,通常會呼叫傳回 Task 物件之方法的多載 WhenAll

注意

對 方法的 WhenAll(IEnumerable<Task>) 呼叫不會封鎖呼叫執行緒。

如果任何提供的工作都以錯誤狀態完成,傳回的工作也會在狀態中 Faulted 完成,其中其例外狀況會包含來自每個所提供工作之未包裝例外狀況集的匯總。

如果沒有提供的工作發生錯誤,但至少其中一個工作已取消,傳回的工作將會以 Canceled 狀態結束。

如果沒有任何工作發生錯誤且未取消任何工作,則產生的工作將會以 RanToCompletion 狀態結束。

如果提供的陣列/可列舉未包含任何工作,傳回的工作將會在傳回給呼叫端之前立即轉換為 RanToCompletion 狀態。

適用於

WhenAll(Task[])

建立一個工作,當陣列中的所有 Task 物件完成時,會完成此工作。

public:
 static System::Threading::Tasks::Task ^ WhenAll(... cli::array <System::Threading::Tasks::Task ^> ^ tasks);
public static System.Threading.Tasks.Task WhenAll (params System.Threading.Tasks.Task[] tasks);
static member WhenAll : System.Threading.Tasks.Task[] -> System.Threading.Tasks.Task
Public Shared Function WhenAll (ParamArray tasks As Task()) As Task

參數

tasks
Task[]

要等待完成的工作。

傳回

Task

工作,代表所有提供的工作已完成。

例外狀況

tasks 引數以前是 null

tasks 陣列以前包含 null 工作。

範例

下列範例會建立一組工作,以偵測陣列中的 URL。 工作會儲存在 List<Task> 轉換成陣列並傳遞至 方法的集合中 WhenAll(IEnumerable<Task>) 。 呼叫 Wait 方法可確保所有線程都已完成之後,此範例會 Task.Status 檢查 屬性,以判斷是否有任何工作發生錯誤。

using System;
using System.Collections.Generic;
using System.Net.NetworkInformation;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   public static async Task Main()
   {
      int failed = 0;
      var tasks = new List<Task>();
      String[] urls = { "www.adatum.com", "www.cohovineyard.com",
                        "www.cohowinery.com", "www.northwindtraders.com",
                        "www.contoso.com" };
      
      foreach (var value in urls) {
         var url = value;
         tasks.Add(Task.Run( () => { var png = new Ping();
                                     try {
                                        var reply = png.Send(url);
                                        if (! (reply.Status == IPStatus.Success)) {
                                           Interlocked.Increment(ref failed);
                                           throw new TimeoutException("Unable to reach " + url + ".");
                                        }
                                     }
                                     catch (PingException) {
                                        Interlocked.Increment(ref failed);
                                        throw;
                                     }
                                   }));
      }
      Task t = Task.WhenAll(tasks.ToArray());
      try {
         await t;
      }
      catch {}   

      if (t.Status == TaskStatus.RanToCompletion)
         Console.WriteLine("All ping attempts succeeded.");
      else if (t.Status == TaskStatus.Faulted)
         Console.WriteLine("{0} ping attempts failed", failed);      
   }
}
// The example displays output like the following:
//       5 ping attempts failed
Imports System.Collections.Generic
Imports System.Net.NetworkInformation
Imports System.Threading
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Dim failed As Integer = 0
      Dim tasks As New List(Of Task)()
      Dim urls() As String = { "www.adatum.com", "www.cohovineyard.com",
                              "www.cohowinery.com", "www.northwindtraders.com",
                              "www.contoso.com" }
      
      For Each value In urls
         Dim url As String = value
         tasks.Add(Task.Run( Sub()
                                Dim png As New Ping()
                                Try
                                   Dim reply = png.Send(url)
                                   If Not reply.Status = IPStatus.Success Then
                                      Interlocked.Increment(failed)
                                      Throw New TimeoutException("Unable to reach " + url + ".")
                                   End If
                                   Catch e As PingException
                                      Interlocked.Increment(failed)
                                      Throw
                                   End Try
                             End Sub))
      Next
      Dim t As Task = Task.WhenAll(tasks.ToArray())
      Try
         t.Wait()
      Catch
      End Try   

      If t.Status = TaskStatus.RanToCompletion
         Console.WriteLine("All ping attempts succeeded.")
      ElseIf t.Status = TaskStatus.Faulted
         Console.WriteLine("{0} ping attempts failed", failed)      
      End If
   End Sub
End Module
' The example displays output like the following:
'     5 ping attempts failed

備註

當您對一組工作的狀態或一組工作擲回的例外狀況感興趣時,通常會呼叫傳回 Task 物件之方法的多載 WhenAll

注意

對 方法的 WhenAll(Task[]) 呼叫不會封鎖呼叫執行緒。

如果任何提供的工作都以錯誤狀態完成,傳回的工作也會在狀態中 Faulted 完成,其中其例外狀況會包含來自每個所提供工作之未包裝例外狀況集的匯總。

如果沒有提供的工作發生錯誤,但至少其中一個工作已取消,傳回的工作將會以 Canceled 狀態結束。

如果沒有任何工作發生錯誤且未取消任何工作,則產生的工作將會以 RanToCompletion 狀態結束。

如果提供的陣列/可列舉未包含任何工作,傳回的工作將會在傳回給呼叫端之前立即轉換為 RanToCompletion 狀態。

適用於

WhenAll<TResult>(IEnumerable<Task<TResult>>)

建立一個工作,當可列舉集合中的所有 Task<TResult> 物件完成時,會完成此工作。

public:
generic <typename TResult>
 static System::Threading::Tasks::Task<cli::array <TResult> ^> ^ WhenAll(System::Collections::Generic::IEnumerable<System::Threading::Tasks::Task<TResult> ^> ^ tasks);
public static System.Threading.Tasks.Task<TResult[]> WhenAll<TResult> (System.Collections.Generic.IEnumerable<System.Threading.Tasks.Task<TResult>> tasks);
static member WhenAll : seq<System.Threading.Tasks.Task<'Result>> -> System.Threading.Tasks.Task<'Result[]>
Public Shared Function WhenAll(Of TResult) (tasks As IEnumerable(Of Task(Of TResult))) As Task(Of TResult())

類型參數

TResult

完成的工作類型。

參數

tasks
IEnumerable<Task<TResult>>

要等待完成的工作。

傳回

Task<TResult[]>

工作,代表所有提供的工作已完成。

例外狀況

tasks 引數以前是 null

tasks 集合以前包含 null 工作。

範例

下列範例會建立 10 個工作,每個工作都會具現化亂數產生器,以在 1 到 1,000 之間建立 1,000 個亂數,並計算其平均數。 方法 Delay(Int32) 可用來延遲亂數產生器的具現化,因此不會使用相同的種子值建立它們。 接著,呼叫 WhenAll 方法會傳回陣列 Int64 ,其中包含每個工作所計算的平均數。 這些接著會用來計算整體平均值。

using System;
using System.Collections.Generic;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      var tasks = new List<Task<long>>();
      for (int ctr = 1; ctr <= 10; ctr++) {
         int delayInterval = 18 * ctr;
         tasks.Add(Task.Run(async () => { long total = 0;
                                          await Task.Delay(delayInterval);
                                          var rnd = new Random();
                                          // Generate 1,000 random numbers.
                                          for (int n = 1; n <= 1000; n++)
                                             total += rnd.Next(0, 1000);
                                          return total; } ));
      }
      var continuation = Task.WhenAll(tasks);
      try {
         continuation.Wait();
      }
      catch (AggregateException)
      { }
   
      if (continuation.Status == TaskStatus.RanToCompletion) {
         long grandTotal = 0;
         foreach (var result in continuation.Result) {
            grandTotal += result;
            Console.WriteLine("Mean: {0:N2}, n = 1,000", result/1000.0);
         }
   
         Console.WriteLine("\nMean of Means: {0:N2}, n = 10,000",
                           grandTotal/10000);
      }
      // Display information on faulted tasks.
      else {
         foreach (var t in tasks) {
            Console.WriteLine("Task {0}: {1}", t.Id, t.Status);
         }
      }
   }
}
// The example displays output like the following:
//       Mean: 506.34, n = 1,000
//       Mean: 504.69, n = 1,000
//       Mean: 489.32, n = 1,000
//       Mean: 505.96, n = 1,000
//       Mean: 515.31, n = 1,000
//       Mean: 499.94, n = 1,000
//       Mean: 496.92, n = 1,000
//       Mean: 508.58, n = 1,000
//       Mean: 494.88, n = 1,000
//       Mean: 493.53, n = 1,000
//
//       Mean of Means: 501.55, n = 10,000
Imports System.Collections.Generic
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Dim tasks As New List(Of Task(Of Long))()
      For ctr As Integer = 1 To 10
         Dim delayInterval As Integer = 18 * ctr
         tasks.Add(Task.Run(Async Function()
                               Dim total As Long = 0
                               Await Task.Delay(delayInterval)
                               Dim rnd As New Random()
                               ' Generate 1,000 random numbers.
                               For n As Integer = 1 To 1000
                                  total += rnd.Next(0, 1000)
                               Next
                               Return total
                            End Function))
      Next
      Dim continuation = Task.WhenAll(tasks)
      Try
         continuation.Wait()
      Catch ae As AggregateException
      End Try
      
      If continuation.Status = TaskStatus.RanToCompletion Then
         Dim grandTotal As Long = 0
         For Each result in continuation.Result
            grandTotal += result
            Console.WriteLine("Mean: {0:N2}, n = 1,000", result/1000)
         Next
         Console.WriteLine()
         Console.WriteLine("Mean of Means: {0:N2}, n = 10,000",
                           grandTotal/10000)
      ' Display information on faulted tasks.
      Else 
         For Each t In tasks
            Console.WriteLine("Task {0}: {1}", t.Id, t.Status)
         Next
      End If
   End Sub
End Module
' The example displays output like the following:
'       Mean: 506.34, n = 1,000
'       Mean: 504.69, n = 1,000
'       Mean: 489.32, n = 1,000
'       Mean: 505.96, n = 1,000
'       Mean: 515.31, n = 1,000
'       Mean: 499.94, n = 1,000
'       Mean: 496.92, n = 1,000
'       Mean: 508.58, n = 1,000
'       Mean: 494.88, n = 1,000
'       Mean: 493.53, n = 1,000
'
'       Mean of Means: 501.55, n = 10,000

在此情況下,十個 List<T> 個別工作會儲存在 物件中。 List<T> 會實作 IEnumerable<T> 介面。

備註

對 方法的 WhenAll<TResult>(IEnumerable<Task<TResult>>) 呼叫不會封鎖呼叫執行緒。 不過,對傳 Result 回之屬性的呼叫會封鎖呼叫執行緒。

如果任何提供的工作都以錯誤狀態完成,傳回的工作也會在狀態中 Faulted 完成,其中其例外狀況會包含來自每個所提供工作之未包裝例外狀況集的匯總。

如果沒有提供的工作發生錯誤,但至少其中一個工作已取消,傳回的工作將會以 Canceled 狀態結束。

如果沒有任何工作發生錯誤且未取消任何工作,則產生的工作將會以 RanToCompletion 狀態結束。 傳 Task<TResult>.Result 回之工作的 屬性會設定為數組,其中包含所提供工作的所有結果,其順序與提供的順序相同 (例如,如果輸入工作陣列包含 t1, t2, t3,則輸出工作的 Task<TResult>.Result 屬性會傳回 TResult[] 其中 arr[0] == t1.Result, arr[1] == t2.Result, and arr[2] == t3.Result)

tasks如果引數不包含任何工作,傳回的工作將會在傳回給呼叫端之前立即轉換為 RanToCompletion 狀態。 傳 TResult[] 回的 將會是 0 個專案的陣列。

適用於

WhenAll<TResult>(Task<TResult>[])

建立一個工作,當陣列中的所有 Task<TResult> 物件完成時,會完成此工作。

public:
generic <typename TResult>
 static System::Threading::Tasks::Task<cli::array <TResult> ^> ^ WhenAll(... cli::array <System::Threading::Tasks::Task<TResult> ^> ^ tasks);
public static System.Threading.Tasks.Task<TResult[]> WhenAll<TResult> (params System.Threading.Tasks.Task<TResult>[] tasks);
static member WhenAll : System.Threading.Tasks.Task<'Result>[] -> System.Threading.Tasks.Task<'Result[]>
Public Shared Function WhenAll(Of TResult) (ParamArray tasks As Task(Of TResult)()) As Task(Of TResult())

類型參數

TResult

完成的工作類型。

參數

tasks
Task<TResult>[]

要等待完成的工作。

傳回

Task<TResult[]>

工作,代表所有提供的工作已完成。

例外狀況

tasks 引數以前是 null

tasks陣列包含 null 工作。

範例

下列範例會建立 10 個工作,每個工作都會具現化亂數產生器,以在 1 到 1,000 之間建立 1,000 個亂數,並計算其平均數。 在此情況下,10 個 Task<Int64> 個別工作會儲存在陣列中。 方法 Delay(Int32) 可用來延遲亂數產生器的具現化,因此不會使用相同的種子值建立它們。 接著,呼叫 WhenAll 方法會傳回陣列 Int64 ,其中包含每個工作所計算的平均數。 這些接著會用來計算整體平均值。

using System;
using System.Collections.Generic;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      var tasks = new Task<long>[10];
      for (int ctr = 1; ctr <= 10; ctr++) {
         int delayInterval = 18 * ctr;
         tasks[ctr - 1] = Task.Run(async () => { long total = 0;
                                                 await Task.Delay(delayInterval);
                                                 var rnd = new Random();
                                                 // Generate 1,000 random numbers.
                                                 for (int n = 1; n <= 1000; n++)
                                                    total += rnd.Next(0, 1000);

                                                 return total; } );
      }
      var continuation = Task.WhenAll(tasks);
      try {
         continuation.Wait();
      }
      catch (AggregateException)
      {}
   
      if (continuation.Status == TaskStatus.RanToCompletion) {
         long grandTotal = 0;
         foreach (var result in continuation.Result) {
            grandTotal += result;
            Console.WriteLine("Mean: {0:N2}, n = 1,000", result/1000.0);
         }
   
         Console.WriteLine("\nMean of Means: {0:N2}, n = 10,000",
                           grandTotal/10000);
      }
      // Display information on faulted tasks.
      else { 
         foreach (var t in tasks)
            Console.WriteLine("Task {0}: {1}", t.Id, t.Status);
      }
   }
}
// The example displays output like the following:
//       Mean: 506.38, n = 1,000
//       Mean: 501.01, n = 1,000
//       Mean: 505.36, n = 1,000
//       Mean: 492.00, n = 1,000
//       Mean: 508.36, n = 1,000
//       Mean: 503.99, n = 1,000
//       Mean: 504.95, n = 1,000
//       Mean: 508.58, n = 1,000
//       Mean: 490.23, n = 1,000
//       Mean: 501.59, n = 1,000
//
//       Mean of Means: 502.00, n = 10,000
Imports System.Collections.Generic
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Dim tasks(9) As Task(Of Long)
      For ctr As Integer = 1 To 10
         Dim delayInterval As Integer = 18 * ctr
         tasks(ctr - 1) =Task.Run(Async Function()
                                     Dim total As Long = 0
                                     Await Task.Delay(delayInterval)
                                     Dim rnd As New Random()
                                     ' Generate 1,000 random numbers.
                                     For n As Integer = 1 To 1000
                                        total += rnd.Next(0, 1000)
                                     Next
                                     Return total
                                  End Function)
      Next
      Dim continuation = Task.WhenAll(tasks)
      Try
         continuation.Wait()
      Catch ae As AggregateException
      End Try
         
      If continuation.Status = TaskStatus.RanToCompletion Then
         Dim grandTotal As Long = 0
         For Each result in continuation.Result
            grandTotal += result
            Console.WriteLine("Mean: {0:N2}, n = 1,000", result/1000)
         Next
         Console.WriteLine()
         Console.WriteLine("Mean of Means: {0:N2}, n = 10,000",
                           grandTotal/10000)
      ' Display information on faulted tasks.
      Else 
         For Each t In tasks
            Console.WriteLine("Task {0}: {1}", t.Id, t.Status)
         Next
      End If
   End Sub
End Module
' The example displays output like the following:
'       Mean: 506.38, n = 1,000
'       Mean: 501.01, n = 1,000
'       Mean: 505.36, n = 1,000
'       Mean: 492.00, n = 1,000
'       Mean: 508.36, n = 1,000
'       Mean: 503.99, n = 1,000
'       Mean: 504.95, n = 1,000
'       Mean: 508.58, n = 1,000
'       Mean: 490.23, n = 1,000
'       Mean: 501.59, n = 1,000
'
'       Mean of Means: 502.00, n = 10,000

備註

對 方法的 WhenAll<TResult>(Task<TResult>[]) 呼叫不會封鎖呼叫執行緒。 不過,對傳 Result 回之屬性的呼叫會封鎖呼叫執行緒。

如果任何提供的工作都以錯誤狀態完成,傳回的工作也會在狀態中 Faulted 完成,其中其例外狀況會包含來自每個所提供工作之未包裝例外狀況集的匯總。

如果沒有提供的工作發生錯誤,但至少其中一個工作已取消,傳回的工作將會以 Canceled 狀態結束。

如果沒有任何工作發生錯誤且未取消任何工作,則產生的工作將會以 RanToCompletion 狀態結束。 Result傳回工作的 將會設定為數組,其中包含所提供工作的所有結果,其順序與提供的順序相同 (,例如,如果輸入工作陣列包含 t1, t2, t3,則輸出工作的 Result 會傳回 TResult[] 其中 arr[0] == t1.Result, arr[1] == t2.Result, and arr[2] == t3.Result)

如果提供的陣列/可列舉未包含任何工作,傳回的工作將會在傳回給呼叫端之前立即轉換為 RanToCompletion 狀態。 傳 TResult[] 回的 將會是 0 個專案的陣列。

適用於