Task.WhenAll Task.WhenAll Task.WhenAll Task.WhenAll Method

定義

指定されたすべてのタスクが完了してから完了するタスクを作成します。Creates a task that will complete when all of the supplied tasks have completed.

オーバーロード

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

列挙可能なコレクション内のすべての Task オブジェクトが完了したときに完了するタスクを作成します。Creates a task that will complete when all of the Task objects in an enumerable collection have completed.

WhenAll(Task[]) WhenAll(Task[]) WhenAll(Task[]) WhenAll(Task[])

配列内のすべての Task オブジェクトが完了したときに完了するタスクを作成します。Creates a task that will complete when all of the Task objects in an array have completed.

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

列挙可能なコレクション内のすべての Task<TResult> オブジェクトが完了したときに完了するタスクを作成します。Creates a task that will complete when all of the Task<TResult> objects in an enumerable collection have completed.

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

配列内のすべての Task<TResult> オブジェクトが完了したときに完了するタスクを作成します。Creates a task that will complete when all of the Task<TResult> objects in an array have completed.

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

列挙可能なコレクション内のすべての Task オブジェクトが完了したときに完了するタスクを作成します。Creates a task that will complete when all of the Task objects in an enumerable collection have completed.

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>

完了を待機するタスク。The tasks to wait on for completion.

戻り値

指定されたすべてのタスクの完了を表すタスク。A task that represents the completion of all of the supplied tasks.

例外

引数 tasksnull でした。The tasks argument was null.

tasks コレクションに null タスクが含まれていました。The tasks collection contained a null task.

次の例では、配列内の Url に ping を行う一連のタスクを作成します。The following example creates a set of tasks that ping the URLs in an array. タスクは、 WhenAll(IEnumerable<Task>)メソッドに渡さList<Task>れるコレクションに格納されます。The tasks are stored in a List<Task> collection that is passed to the WhenAll(IEnumerable<Task>) method. Waitメソッドを呼び出すと、すべてのスレッドが完了したことが確認さTask.Statusれた後、この例では、プロパティを調べて、いずれかのタスクが失敗したかどうかを判断します。After the call to the Wait method ensures that all threads have completed, the example examines the Task.Status property to determine whether any tasks have faulted.

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

注釈

オブジェクトをWhenAll Task返すメソッドのオーバーロードは、通常、一連のタスクの状態または一連のタスクによってスローされる例外に関心がある場合に呼び出されます。The overloads of the WhenAll method that return a Task object are typically called when you are interested in the status of a set of tasks or in the exceptions thrown by a set of tasks.

注意

メソッドをWhenAll(IEnumerable<Task>)呼び出すと、呼び出し元のスレッドがブロックされません。The call to WhenAll(IEnumerable<Task>) method does not block the calling thread.

指定されたいずれかのタスクが faulted 状態で完了した場合は、返されFaultedたタスクも状態で完了します。その例外には、指定された各タスクからのラップされていない例外の集合が含まれます。If any of the supplied tasks completes in a faulted state, the returned task will also complete in a Faulted state, where its exceptions will contain the aggregation of the set of unwrapped exceptions from each of the supplied tasks.

指定されたタスクがいずれも失敗しても、そのうち少なくとも1つが取り消されCanceledた場合、返されたタスクは状態で終了します。If none of the supplied tasks faulted but at least one of them was canceled, the returned task will end in the Canceled state.

タスクにエラーが発生しておらず、どのタスクも取り消されなかった場合、結果のRanToCompletionタスクは状態で終了します。If none of the tasks faulted and none of the tasks were canceled, the resulting task will end in the RanToCompletion state.

指定した配列または列挙可能なにタスクが含まれていない場合RanToCompletion 、返されるタスクは、呼び出し元に返される前に直ちに状態に遷移します。If the supplied array/enumerable contains no tasks, the returned task will immediately transition to a RanToCompletion state before it's returned to the caller.

WhenAll(Task[]) WhenAll(Task[]) WhenAll(Task[]) WhenAll(Task[])

配列内のすべての Task オブジェクトが完了したときに完了するタスクを作成します。Creates a task that will complete when all of the Task objects in an array have completed.

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[]

完了を待機するタスク。The tasks to wait on for completion.

戻り値

指定されたすべてのタスクの完了を表すタスク。A task that represents the completion of all of the supplied tasks.

例外

引数 tasksnull でした。The tasks argument was null.

tasks 配列に null タスクが含まれていました。The tasks array contained a null task.

次の例では、配列内の Url に ping を行う一連のタスクを作成します。The following example creates a set of tasks that ping the URLs in an array. タスクは、配列に変換List<Task>され、 WhenAll(IEnumerable<Task>)メソッドに渡されるコレクションに格納されます。The tasks are stored in a List<Task> collection that is converted to an array and passed to the WhenAll(IEnumerable<Task>) method. Waitメソッドを呼び出すと、すべてのスレッドが完了したことが確認さTask.Statusれた後、この例では、プロパティを調べて、いずれかのタスクが失敗したかどうかを判断します。After the call to the Wait method ensures that all threads have completed, the example examines the Task.Status property to determine whether any tasks have faulted.

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

注釈

オブジェクトをWhenAll Task返すメソッドのオーバーロードは、通常、一連のタスクの状態または一連のタスクによってスローされる例外に関心がある場合に呼び出されます。The overloads of the WhenAll method that return a Task object are typically called when you are interested in the status of a set of tasks or in the exceptions thrown by a set of tasks.

注意

メソッドをWhenAll(Task[])呼び出すと、呼び出し元のスレッドがブロックされません。The call to WhenAll(Task[]) method does not block the calling thread.

指定されたいずれかのタスクが faulted 状態で完了した場合は、返されFaultedたタスクも状態で完了します。その例外には、指定された各タスクからのラップされていない例外の集合が含まれます。If any of the supplied tasks completes in a faulted state, the returned task will also complete in a Faulted state, where its exceptions will contain the aggregation of the set of unwrapped exceptions from each of the supplied tasks.

指定されたタスクがいずれも失敗しても、そのうち少なくとも1つが取り消されCanceledた場合、返されたタスクは状態で終了します。If none of the supplied tasks faulted but at least one of them was canceled, the returned task will end in the Canceled state.

タスクにエラーが発生しておらず、どのタスクも取り消されなかった場合、結果のRanToCompletionタスクは状態で終了します。If none of the tasks faulted and none of the tasks were canceled, the resulting task will end in the RanToCompletion state.

指定した配列または列挙可能なにタスクが含まれていない場合RanToCompletion 、返されるタスクは、呼び出し元に返される前に直ちに状態に遷移します。If the supplied array/enumerable contains no tasks, the returned task will immediately transition to a RanToCompletion state before it's returned to the caller.

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

列挙可能なコレクション内のすべての Task<TResult> オブジェクトが完了したときに完了するタスクを作成します。Creates a task that will complete when all of the Task<TResult> objects in an enumerable collection have completed.

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

完了したタスクの型。The type of the completed task.

パラメーター

tasks
IEnumerable<Task<TResult>>

完了を待機するタスク。The tasks to wait on for completion.

戻り値

Task<TResult[]>

指定されたすべてのタスクの完了を表すタスク。A task that represents the completion of all of the supplied tasks.

例外

引数 tasksnull でした。The tasks argument was null.

tasks コレクションに null タスクが含まれていました。The tasks collection contained a null task.

次の例では、10個のタスクを作成し、1 ~ 1000 の範囲で1000の乱数を作成し、平均を計算する乱数ジェネレーターをインスタンス化します。The following example creates ten tasks, each of which instantiates a random number generator that creates 1,000 random numbers between 1 and 1,000 and computes their mean. メソッドDelay(Int32)は、乱数ジェネレーターのインスタンス化を遅延させ、同じシード値で作成されないようにするために使用されます。The Delay(Int32) method is used to delay instantiation of the random number generators so that they are not created with identical seed values. 次に、 WhenAllメソッドを呼び出すとInt64 、各タスクによって計算された平均値を含む配列が返されます。The call to the WhenAll method then returns an Int64 array that contains the mean computed by each task. これらは、全体の平均を計算するために使用されます。These are then used to calculate the overall mean.

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

この場合、10個の個別のタスクがList<T>オブジェクトに格納されます。In this case, the ten individual tasks are stored in a List<T> object. List<T> では、IEnumerable<T> インターフェイスを実装します。List<T> implements the IEnumerable<T> interface.

注釈

メソッドをWhenAll<TResult>(IEnumerable<Task<TResult>>)呼び出すと、呼び出し元のスレッドがブロックされません。The call to WhenAll<TResult>(IEnumerable<Task<TResult>>) method does not block the calling thread. ただし、返されResultたプロパティを呼び出すと、呼び出し元のスレッドがブロックされます。However, a call to the returned Result property does block the calling thread.

指定されたいずれかのタスクが faulted 状態で完了した場合は、返されFaultedたタスクも状態で完了します。その例外には、指定された各タスクからのラップされていない例外の集合が含まれます。If any of the supplied tasks completes in a faulted state, the returned task will also complete in a Faulted state, where its exceptions will contain the aggregation of the set of unwrapped exceptions from each of the supplied tasks.

指定されたタスクがいずれも失敗しても、そのうち少なくとも1つが取り消されCanceledた場合、返されたタスクは状態で終了します。If none of the supplied tasks faulted but at least one of them was canceled, the returned task will end in the Canceled state.

タスクにエラーが発生しておらず、どのタスクも取り消されなかった場合、結果のRanToCompletionタスクは状態で終了します。If none of the tasks faulted and none of the tasks were canceled, the resulting task will end in the RanToCompletion state. 返されたタスクのTask<TResult>.Result プロパティは、指定されたタスクのすべての結果を含む配列に設定されます(たとえば、入力タスク配列にt1、t2、t3が含まれていた場合、出力タスクのプロパティはを返します)。Task<TResult>.ResultTResult[]指定します。 arr[0] == t1.Result, arr[1] == t2.Result, and arr[2] == t3.Result)The Task<TResult>.Result property of the returned task will be set to an array containing all of the results of the supplied tasks in the same order as they were provided (e.g. if the input tasks array contained t1, t2, t3, the output task's Task<TResult>.Result property will return an TResult[] where arr[0] == t1.Result, arr[1] == t2.Result, and arr[2] == t3.Result).

引数にtasksタスクが含まれていない場合、返されるタスクはRanToCompletion 、呼び出し元に返される前に直ちに状態に遷移します。If the tasks argument contains no tasks, the returned task will immediately transition to a RanToCompletion state before it's returned to the caller. 返さTResult[]れるは、0個の要素の配列になります。The returned TResult[] will be an array of 0 elements.

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

配列内のすべての Task<TResult> オブジェクトが完了したときに完了するタスクを作成します。Creates a task that will complete when all of the Task<TResult> objects in an array have completed.

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

完了したタスクの型。The type of the completed task.

パラメーター

tasks
Task<TResult>[]

完了を待機するタスク。The tasks to wait on for completion.

戻り値

Task<TResult[]>

指定されたすべてのタスクの完了を表すタスク。A task that represents the completion of all of the supplied tasks.

例外

引数 tasksnull でした。The tasks argument was null.

tasks 配列に null タスクが含まれていました。The tasks array contained a null task.

次の例では、10個のタスクを作成し、1 ~ 1000 の範囲で1000の乱数を作成し、平均を計算する乱数ジェネレーターをインスタンス化します。The following example creates ten tasks, each of which instantiates a random number generator that creates 1,000 random numbers between 1 and 1,000 and computes their mean. この場合、10個の個別のタスクがTask<Int64>配列に格納されます。In this case, the ten individual tasks are stored in a Task<Int64> array. メソッドDelay(Int32)は、乱数ジェネレーターのインスタンス化を遅延させ、同じシード値で作成されないようにするために使用されます。The Delay(Int32) method is used to delay instantiation of the random number generators so that they are not created with identical seed values. 次に、 WhenAllメソッドを呼び出すとInt64 、各タスクによって計算された平均値を含む配列が返されます。The call to the WhenAll method then returns an Int64 array that contains the mean computed by each task. これらは、全体の平均を計算するために使用されます。These are then used to calculate the overall mean.

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>[])呼び出すと、呼び出し元のスレッドがブロックされません。The call to WhenAll<TResult>(Task<TResult>[]) method does not block the calling thread. ただし、返されResultたプロパティを呼び出すと、呼び出し元のスレッドがブロックされます。However, a call to the returned Result property does block the calling thread.

指定されたいずれかのタスクが faulted 状態で完了した場合は、返されFaultedたタスクも状態で完了します。その例外には、指定された各タスクからのラップされていない例外の集合が含まれます。If any of the supplied tasks completes in a faulted state, the returned task will also complete in a Faulted state, where its exceptions will contain the aggregation of the set of unwrapped exceptions from each of the supplied tasks.

指定されたタスクがいずれも失敗しても、そのうち少なくとも1つが取り消されCanceledた場合、返されたタスクは状態で終了します。If none of the supplied tasks faulted but at least one of them was canceled, the returned task will end in the Canceled state.

タスクにエラーが発生しておらず、どのタスクも取り消されなかった場合、結果のRanToCompletionタスクは状態で終了します。If none of the tasks faulted and none of the tasks were canceled, the resulting task will end in the RanToCompletion state. 返さResultれたタスクのは、指定されたタスクのすべての結果を含む配列に設定されます。たとえば、入力タスク配列に t1、t2、t3 が含まれている場合、出力ResultタスクTResult[]はwhere arr[0] == t1.Result, arr[1] == t2.Result, and arr[2] == t3.Result)The Result of the returned task will be set to an array containing all of the results of the supplied tasks in the same order as they were provided (e.g. if the input tasks array contained t1, t2, t3, the output task's Result will return an TResult[] where arr[0] == t1.Result, arr[1] == t2.Result, and arr[2] == t3.Result).

指定した配列または列挙可能なにタスクが含まれていない場合RanToCompletion 、返されるタスクは、呼び出し元に返される前に直ちに状態に遷移します。If the supplied array/enumerable contains no tasks, the returned task will immediately transition to a RanToCompletion state before it's returned to the caller. 返さTResult[]れるは、0個の要素の配列になります。The returned TResult[] will be an array of 0 elements.

適用対象