Task.WhenAll Método

Definición

Crea una tarea que se completará cuando se hayan completado todas las tareas proporcionadas.Creates a task that will complete when all of the supplied tasks have completed.

Sobrecargas

WhenAll(IEnumerable<Task>)

Crea una tarea que se completará cuando todos los objetos Task de una colección enumerable se hayan completado.Creates a task that will complete when all of the Task objects in an enumerable collection have completed.

WhenAll(Task[])

Crea una tarea que se completará cuando todos los objetos Task de una matriz se hayan completado.Creates a task that will complete when all of the Task objects in an array have completed.

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

Crea una tarea que se completará cuando todos los objetos Task<TResult> de una colección enumerable se hayan completado.Creates a task that will complete when all of the Task<TResult> objects in an enumerable collection have completed.

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

Crea una tarea que se completará cuando todos los objetos Task<TResult> de una matriz se hayan completado.Creates a task that will complete when all of the Task<TResult> objects in an array have completed.

WhenAll(IEnumerable<Task>)

Crea una tarea que se completará cuando todos los objetos Task de una colección enumerable se hayan completado.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

Parámetros

tasks
IEnumerable<Task>

Tareas cuya finalización hay que esperar.The tasks to wait on for completion.

Devoluciones

Task

Tarea que representa la finalización de todas las tareas proporcionadas.A task that represents the completion of all of the supplied tasks.

Excepciones

El argumento tasks era null.The tasks argument was null.

La colección tasks contiene una tarea null.The tasks collection contained a null task.

Ejemplos

En el ejemplo siguiente se crea un conjunto de tareas que hacen ping a las direcciones URL de una matriz.The following example creates a set of tasks that ping the URLs in an array. Las tareas se almacenan en una List<Task> colección que se pasa al WhenAll(IEnumerable<Task>) método.The tasks are stored in a List<Task> collection that is passed to the WhenAll(IEnumerable<Task>) method. Después de que la llamada al Wait método garantiza que todos los subprocesos se han completado, el ejemplo examina la Task.Status propiedad para determinar si se ha producido un error en alguna de las tareas.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

Comentarios

WhenAllNormalmente, se llama a las sobrecargas del método que devuelven un Task objeto cuando está interesado en el estado de un conjunto de tareas o en las excepciones producidas por un conjunto de tareas.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.

Nota

La llamada a WhenAll(IEnumerable<Task>) método no bloquea el subproceso que realiza la llamada.The call to WhenAll(IEnumerable<Task>) method does not block the calling thread.

Si alguna de las tareas proporcionadas se completa en un estado de error, la tarea devuelta también se completará en un Faulted Estado, donde sus excepciones contendrán la agregación del conjunto de excepciones desencapsuladas de cada una de las tareas proporcionadas.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.

Si no se ha producido ningún error en ninguna de las tareas proporcionadas pero se canceló al menos una de ellas, la tarea devuelta finalizará en el Canceled Estado.If none of the supplied tasks faulted but at least one of them was canceled, the returned task will end in the Canceled state.

Si no se ha producido ningún error en ninguna de las tareas y ninguna de las tareas se ha cancelado, la tarea resultante finalizará en el RanToCompletion Estado.If none of the tasks faulted and none of the tasks were canceled, the resulting task will end in the RanToCompletion state.

Si la matriz o Enumerable proporcionada no contiene ninguna tarea, la tarea devuelta pasará inmediatamente a un RanToCompletion estado antes de que se devuelva al autor de la llamada.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.

Se aplica a

WhenAll(Task[])

Crea una tarea que se completará cuando todos los objetos Task de una matriz se hayan completado.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

Parámetros

tasks
Task[]

Tareas cuya finalización hay que esperar.The tasks to wait on for completion.

Devoluciones

Task

Tarea que representa la finalización de todas las tareas proporcionadas.A task that represents the completion of all of the supplied tasks.

Excepciones

El argumento tasks era null.The tasks argument was null.

La matriz tasks contenía una tarea null.The tasks array contained a null task.

Ejemplos

En el ejemplo siguiente se crea un conjunto de tareas que hacen ping a las direcciones URL de una matriz.The following example creates a set of tasks that ping the URLs in an array. Las tareas se almacenan en una List<Task> colección que se convierte en una matriz y se pasa al WhenAll(IEnumerable<Task>) método.The tasks are stored in a List<Task> collection that is converted to an array and passed to the WhenAll(IEnumerable<Task>) method. Después de que la llamada al Wait método garantiza que todos los subprocesos se han completado, el ejemplo examina la Task.Status propiedad para determinar si se ha producido un error en alguna de las tareas.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

Comentarios

WhenAllNormalmente, se llama a las sobrecargas del método que devuelven un Task objeto cuando está interesado en el estado de un conjunto de tareas o en las excepciones producidas por un conjunto de tareas.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.

Nota

La llamada a WhenAll(Task[]) método no bloquea el subproceso que realiza la llamada.The call to WhenAll(Task[]) method does not block the calling thread.

Si alguna de las tareas proporcionadas se completa en un estado de error, la tarea devuelta también se completará en un Faulted Estado, donde sus excepciones contendrán la agregación del conjunto de excepciones desencapsuladas de cada una de las tareas proporcionadas.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.

Si no se ha producido ningún error en ninguna de las tareas proporcionadas pero se canceló al menos una de ellas, la tarea devuelta finalizará en el Canceled Estado.If none of the supplied tasks faulted but at least one of them was canceled, the returned task will end in the Canceled state.

Si no se ha producido ningún error en ninguna de las tareas y ninguna de las tareas se ha cancelado, la tarea resultante finalizará en el RanToCompletion Estado.If none of the tasks faulted and none of the tasks were canceled, the resulting task will end in the RanToCompletion state.

Si la matriz o Enumerable proporcionada no contiene ninguna tarea, la tarea devuelta pasará inmediatamente a un RanToCompletion estado antes de que se devuelva al autor de la llamada.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.

Se aplica a

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

Crea una tarea que se completará cuando todos los objetos Task<TResult> de una colección enumerable se hayan completado.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())

Parámetros de tipo

TResult

Tipo de la tarea completada.The type of the completed task.

Parámetros

tasks
IEnumerable<Task<TResult>>

Tareas cuya finalización hay que esperar.The tasks to wait on for completion.

Devoluciones

Task<TResult[]>

Tarea que representa la finalización de todas las tareas proporcionadas.A task that represents the completion of all of the supplied tasks.

Excepciones

El argumento tasks era null.The tasks argument was null.

La colección tasks contenía una tarea null.The tasks collection contained a null task.

Ejemplos

En el ejemplo siguiente se crean diez tareas, cada una de las cuales crea una instancia de un generador de números aleatorios que crea 1.000 números aleatorios entre 1 y 1.000 y calcula su media.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. El Delay(Int32) método se usa para retrasar la creación de instancias de los generadores de números aleatorios para que no se creen con valores de inicialización idénticos.The Delay(Int32) method is used to delay instantiation of the random number generators so that they are not created with identical seed values. WhenAllA continuación, la llamada al método devuelve una Int64 matriz que contiene la media calculada por cada tarea.The call to the WhenAll method then returns an Int64 array that contains the mean computed by each task. A continuación, se utilizan para calcular la media global.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

En este caso, las diez tareas individuales se almacenan en un List<T> objeto.In this case, the ten individual tasks are stored in a List<T> object. List<T> implementa la interfaz IEnumerable<T>.List<T> implements the IEnumerable<T> interface.

Comentarios

La llamada a WhenAll<TResult>(IEnumerable<Task<TResult>>) método no bloquea el subproceso que realiza la llamada.The call to WhenAll<TResult>(IEnumerable<Task<TResult>>) method does not block the calling thread. Sin embargo, una llamada a la Result propiedad devuelta bloquea el subproceso que realiza la llamada.However, a call to the returned Result property does block the calling thread.

Si alguna de las tareas proporcionadas se completa en un estado de error, la tarea devuelta también se completará en un Faulted Estado, donde sus excepciones contendrán la agregación del conjunto de excepciones desencapsuladas de cada una de las tareas proporcionadas.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.

Si no se ha producido ningún error en ninguna de las tareas proporcionadas pero se canceló al menos una de ellas, la tarea devuelta finalizará en el Canceled Estado.If none of the supplied tasks faulted but at least one of them was canceled, the returned task will end in the Canceled state.

Si no se ha producido ningún error en ninguna de las tareas y ninguna de las tareas se ha cancelado, la tarea resultante finalizará en el RanToCompletion Estado.If none of the tasks faulted and none of the tasks were canceled, the resulting task will end in the RanToCompletion state. La Task<TResult>.Result propiedad de la tarea devuelta se establecerá en una matriz que contenga todos los resultados de las tareas proporcionadas en el mismo orden en que se proporcionaron (por ejemplo, si la matriz de tareas de entrada contenía T1, T2, T3, la propiedad de la tarea de salida Task<TResult>.Result devolverá un TResult[] donde 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).

Si el tasks argumento no contiene tareas, la tarea devuelta pasará inmediatamente a un RanToCompletion estado antes de que se devuelva al autor de la llamada.If the tasks argument contains no tasks, the returned task will immediately transition to a RanToCompletion state before it's returned to the caller. El valor devuelto será TResult[] una matriz de 0 elementos.The returned TResult[] will be an array of 0 elements.

Se aplica a

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

Crea una tarea que se completará cuando todos los objetos Task<TResult> de una matriz se hayan completado.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())

Parámetros de tipo

TResult

Tipo de la tarea completada.The type of the completed task.

Parámetros

tasks
Task<TResult>[]

Tareas cuya finalización hay que esperar.The tasks to wait on for completion.

Devoluciones

Task<TResult[]>

Tarea que representa la finalización de todas las tareas proporcionadas.A task that represents the completion of all of the supplied tasks.

Excepciones

El argumento tasks era null.The tasks argument was null.

La matriz tasks contiene una tarea null.The tasks array contained a null task.

Ejemplos

En el ejemplo siguiente se crean diez tareas, cada una de las cuales crea una instancia de un generador de números aleatorios que crea 1.000 números aleatorios entre 1 y 1.000 y calcula su media.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. En este caso, las diez tareas individuales se almacenan en una Task<Int64> matriz.In this case, the ten individual tasks are stored in a Task<Int64> array. El Delay(Int32) método se usa para retrasar la creación de instancias de los generadores de números aleatorios para que no se creen con valores de inicialización idénticos.The Delay(Int32) method is used to delay instantiation of the random number generators so that they are not created with identical seed values. WhenAllA continuación, la llamada al método devuelve una Int64 matriz que contiene la media calculada por cada tarea.The call to the WhenAll method then returns an Int64 array that contains the mean computed by each task. A continuación, se utilizan para calcular la media global.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

Comentarios

La llamada a WhenAll<TResult>(Task<TResult>[]) método no bloquea el subproceso que realiza la llamada.The call to WhenAll<TResult>(Task<TResult>[]) method does not block the calling thread. Sin embargo, una llamada a la Result propiedad devuelta bloquea el subproceso que realiza la llamada.However, a call to the returned Result property does block the calling thread.

Si alguna de las tareas proporcionadas se completa en un estado de error, la tarea devuelta también se completará en un Faulted Estado, donde sus excepciones contendrán la agregación del conjunto de excepciones desencapsuladas de cada una de las tareas proporcionadas.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.

Si no se ha producido ningún error en ninguna de las tareas proporcionadas pero se canceló al menos una de ellas, la tarea devuelta finalizará en el Canceled Estado.If none of the supplied tasks faulted but at least one of them was canceled, the returned task will end in the Canceled state.

Si no se ha producido ningún error en ninguna de las tareas y ninguna de las tareas se ha cancelado, la tarea resultante finalizará en el RanToCompletion Estado.If none of the tasks faulted and none of the tasks were canceled, the resulting task will end in the RanToCompletion state. La Result de la tarea devuelta se establecerá en una matriz que contenga todos los resultados de las tareas proporcionadas en el mismo orden en que se proporcionaron (por ejemplo, si la matriz de tareas de entrada contenía T1, T2, T3, la tarea de salida Result devolverá 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).

Si la matriz o Enumerable proporcionada no contiene ninguna tarea, la tarea devuelta pasará inmediatamente a un RanToCompletion estado antes de que se devuelva al autor de la llamada.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. El valor devuelto será TResult[] una matriz de 0 elementos.The returned TResult[] will be an array of 0 elements.

Se aplica a