Task.WhenAll Metodo

Definizione

Crea un'attività che verrà completata quando tutte le attività fornite saranno completate.

Overload

WhenAll(IEnumerable<Task>)

Crea un'attività che verrà completata in seguito al completamento di tutti gli oggetti Task in una raccolta enumerabile.

WhenAll(Task[])

Crea un'attività che verrà completata in seguito al completamento di tutti gli oggetti Task in una matrice.

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

Crea un'attività che verrà completata in seguito al completamento di tutti gli oggetti Task<TResult> in una raccolta enumerabile.

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

Crea un'attività che verrà completata in seguito al completamento di tutti gli oggetti Task<TResult> in una matrice.

WhenAll(IEnumerable<Task>)

Crea un'attività che verrà completata in seguito al completamento di tutti gli oggetti Task in una raccolta enumerabile.

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

Parametri

tasks
IEnumerable<Task>

Le attività in attesa del completamento.

Restituisce

Attività che rappresenta il completamento di tutte le attività fornite.

Eccezioni

Il valore dell'argomento tasks è null.

La raccolta tasks conteneva un'attività null.

Esempio

Nell'esempio seguente viene creato un set di attività che esegue il ping degli URL in una matrice. Le attività vengono archiviate in una List<Task> raccolta passata al WhenAll(IEnumerable<Task>) metodo. Dopo la chiamata al Wait metodo garantisce che tutti i thread siano stati completati, nell'esempio viene esaminata la Task.Status proprietà per determinare se le attività hanno avuto errori.

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
open System
open System.Net.NetworkInformation
open System.Threading
open System.Threading.Tasks

let mutable failed = 0

let urls =
    [ "www.adatum.com"
      "www.cohovineyard.com"
      "www.cohowinery.com"
      "www.northwindtraders.com"
      "www.contoso.com" ]

let tasks =
    urls
    |> List.map (fun url ->
        Task.Run(fun () ->
            let png = new Ping()

            try
                let reply = png.Send url

                if reply.Status <> IPStatus.Success then
                    Interlocked.Increment &failed |> ignore
                    raise (TimeoutException $"Unable to reach {url}.")
            with :? PingException ->
                Interlocked.Increment &failed |> ignore
                reraise ()))

let t = Task.WhenAll tasks

try
    t.Wait()
with _ ->
    ()

if t.Status = TaskStatus.RanToCompletion then
    printfn "All ping attempts succeeded."
elif t.Status = TaskStatus.Faulted then
    printfn $"{failed} ping attempts 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

Commenti

Gli overload del WhenAll metodo che restituiscono un Task oggetto vengono in genere chiamati quando si è interessati allo stato di un set di attività o nelle eccezioni generate da un set di attività.

Nota

La chiamata al WhenAll(IEnumerable<Task>) metodo non blocca il thread chiamante.

Se una delle attività fornite viene completata in uno stato di errore, l'attività restituita verrà completata anche in uno Faulted stato, in cui le eccezioni conterrà l'aggregazione del set di eccezioni non elaborate da ognuna delle attività fornite.

Se nessuna delle attività specificate è stata annullata, ma almeno una di esse è stata annullata, l'attività restituita termina nello Canceled stato.

Se nessuna delle attività è stata annullata e nessuna delle attività è stata annullata, l'attività RanToCompletion risultante termina nello stato.

Se la matrice/enumerabile fornita non contiene attività, l'attività restituita passerà immediatamente a uno RanToCompletion stato prima di tornare al chiamante.

Si applica a

WhenAll(Task[])

Crea un'attività che verrà completata in seguito al completamento di tutti gli oggetti Task in una matrice.

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

Parametri

tasks
Task[]

Attività in attesa del completamento.

Restituisce

Attività che rappresenta il completamento di tutte le attività fornite.

Eccezioni

Il valore dell'argomento tasks è null.

La matricetasks conteneva un'attività null.

Esempio

Nell'esempio seguente viene creato un set di attività che esegue il ping degli URL in una matrice. Le attività vengono archiviate in una raccolta convertita in una List<Task> matrice e passata al WhenAll(IEnumerable<Task>) metodo. Dopo la chiamata al Wait metodo garantisce che tutti i thread siano stati completati, nell'esempio viene esaminata la Task.Status proprietà per determinare se le attività hanno avuto errori.

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
open System
open System.Net.NetworkInformation
open System.Threading
open System.Threading.Tasks

let mutable failed = 0

let urls =
    [| "www.adatum.com"
       "www.cohovineyard.com"
       "www.cohowinery.com"
       "www.northwindtraders.com"
       "www.contoso.com" |]

let tasks =
    urls
    |> Array.map (fun url ->
        Task.Run(fun () ->
            let png = new Ping()

            try
                let reply = png.Send url

                if reply.Status <> IPStatus.Success then
                    Interlocked.Increment &failed |> ignore
                    raise (TimeoutException $"Unable to reach {url}.")
            with :? PingException ->
                Interlocked.Increment &failed |> ignore
                reraise ()))

let main =
    task {
        let t = Task.WhenAll tasks

        try
            do! t
        with _ ->
            ()

        if t.Status = TaskStatus.RanToCompletion then
            printfn "All ping attempts succeeded."
        elif t.Status = TaskStatus.Faulted then
            printfn $"{failed} ping attempts failed"
    }

main.Wait()
// 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

Commenti

Gli overload del WhenAll metodo che restituiscono un Task oggetto vengono in genere chiamati quando si è interessati allo stato di un set di attività o nelle eccezioni generate da un set di attività.

Nota

La chiamata al WhenAll(Task[]) metodo non blocca il thread chiamante.

Se una delle attività fornite viene completata in uno stato di errore, l'attività restituita verrà completata anche in uno Faulted stato, in cui le eccezioni conterrà l'aggregazione del set di eccezioni non elaborate da ognuna delle attività fornite.

Se nessuna delle attività specificate è stata annullata, ma almeno una di esse è stata annullata, l'attività restituita termina nello Canceled stato.

Se nessuna delle attività è stata annullata e nessuna delle attività è stata annullata, l'attività RanToCompletion risultante termina nello stato.

Se la matrice/enumerabile fornita non contiene attività, l'attività restituita passerà immediatamente a uno RanToCompletion stato prima di tornare al chiamante.

Si applica a

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

Crea un'attività che verrà completata in seguito al completamento di tutti gli oggetti Task<TResult> in una raccolta enumerabile.

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())

Parametri di tipo

TResult

Tipo dell'attività completata.

Parametri

tasks
IEnumerable<Task<TResult>>

Le attività in attesa del completamento.

Restituisce

Task<TResult[]>

Attività che rappresenta il completamento di tutte le attività fornite.

Eccezioni

Il valore dell'argomento tasks è null.

La raccolta tasks conteneva un'attività null.

Esempio

Nell'esempio seguente vengono create dieci attività, ognuna delle quali crea un'istanza di un generatore di numeri casuali che crea 1.000 numeri casuali compresi tra 1 e 1.000 e calcola la loro media. Il Delay(Int32) metodo viene usato per ritardare l'istanza dei generatori di numeri casuali in modo che non vengano creati con valori di inizializzazione identici. La chiamata al WhenAll metodo restituisce quindi una Int64 matrice contenente la media calcolata da ogni attività. Questi vengono quindi usati per calcolare la media complessiva.

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
open System
open System.Threading.Tasks

let tasks =
    [| for i = 1 to 10 do
           let delayInterval = 18 * i

           task {
               let mutable total = 0L
               do! Task.Delay delayInterval
               let rnd = Random()

               for _ = 1 to 1000 do
                   total <- total + (rnd.Next(0, 1000) |> int64)

               return total
           } |]

let continuation = Task.WhenAll tasks

try
    continuation.Wait()

with :? AggregateException ->
    ()

if continuation.Status = TaskStatus.RanToCompletion then
    for result in continuation.Result do
        printfn $"Mean: {float result / 1000.:N2}, n = 1,000"

    let grandTotal = continuation.Result |> Array.sum

    printfn $"\nMean of Means: {float grandTotal / 10000.:N2}, n = 10,000"

// Display information on faulted tasks.
else
    for t in tasks do
        printfn $"Task {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

In questo caso, le dieci singole attività vengono archiviate in un List<T> oggetto. L'oggetto List<T> implementa l'interfaccia IEnumerable<T>.

Commenti

La chiamata al WhenAll<TResult>(IEnumerable<Task<TResult>>) metodo non blocca il thread chiamante. Tuttavia, una chiamata alla proprietà restituita blocca il thread chiamante Result .

Se una delle attività fornite viene completata in uno stato di errore, l'attività restituita verrà completata anche in uno Faulted stato, in cui le eccezioni conterrà l'aggregazione del set di eccezioni non elaborate da ognuna delle attività fornite.

Se nessuna delle attività specificate è stata annullata, ma almeno una di esse è stata annullata, l'attività restituita termina nello Canceled stato.

Se nessuna delle attività è stata annullata e nessuna delle attività è stata annullata, l'attività RanToCompletion risultante termina nello stato. La Task<TResult>.Result proprietà dell'attività restituita verrà impostata su una matrice contenente tutti i risultati delle attività fornite nello stesso ordine specificato, ad esempio se la matrice di attività di input contiene t1, t2, t3, la proprietà dell'attività Task<TResult>.Result di output restituirà un TResult[] dove arr[0] == t1.Result, arr[1] == t2.Result, and arr[2] == t3.Result).

Se l'argomento non contiene attività, l'attività tasks restituita passerà immediatamente a uno RanToCompletion stato prima che venga restituito al chiamante. Il restituito TResult[] sarà una matrice di 0 elementi.

Si applica a

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

Crea un'attività che verrà completata in seguito al completamento di tutti gli oggetti Task<TResult> in una matrice.

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())

Parametri di tipo

TResult

Tipo dell'attività completata.

Parametri

tasks
Task<TResult>[]

Attività in attesa del completamento.

Restituisce

Task<TResult[]>

Attività che rappresenta il completamento di tutte le attività fornite.

Eccezioni

Il valore dell'argomento tasks è null.

La matricetasks conteneva un'attività null.

Esempio

Nell'esempio seguente vengono create dieci attività, ognuna delle quali crea un'istanza di un generatore di numeri casuali che crea 1.000 numeri casuali compresi tra 1 e 1.000 e calcola la loro media. In questo caso, le dieci singole attività vengono archiviate in una Task<Int64> matrice. Il Delay(Int32) metodo viene usato per ritardare l'istanza dei generatori di numeri casuali in modo che non vengano creati con valori di inizializzazione identici. La chiamata al WhenAll metodo restituisce quindi una Int64 matrice contenente la media calcolata da ogni attività. Questi vengono quindi usati per calcolare la media complessiva.

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
open System
open System.Threading.Tasks

let tasks =
    [| for i = 1 to 10 do
           let delayInterval = 18 * i

           task {
               let mutable total = 0L
               do! Task.Delay delayInterval
               let rnd = Random()

               for _ = 1 to 1000 do
                   total <- total + (rnd.Next(0, 1000) |> int64)

               return total
           } |]

let continuation = Task.WhenAll tasks

try
    continuation.Wait()

with :? AggregateException ->
    ()

if continuation.Status = TaskStatus.RanToCompletion then
    for result in continuation.Result do
        printfn $"Mean: {float result / 1000.:N2}, n = 1,000"

    let grandTotal = Array.sum continuation.Result

    printfn $"\nMean of Means: {float grandTotal / 10000.:N2}, n = 10,000"

// Display information on faulted tasks.
else
    for t in tasks do
        printfn $"Task {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

Commenti

La chiamata al WhenAll<TResult>(Task<TResult>[]) metodo non blocca il thread chiamante. Tuttavia, una chiamata alla proprietà restituita blocca il thread chiamante Result .

Se una delle attività fornite viene completata in uno stato di errore, l'attività restituita verrà completata anche in uno Faulted stato, in cui le eccezioni conterrà l'aggregazione del set di eccezioni non elaborate da ognuna delle attività fornite.

Se nessuna delle attività specificate è stata annullata, ma almeno una di esse è stata annullata, l'attività restituita termina nello Canceled stato.

Se nessuna delle attività è stata annullata e nessuna delle attività è stata annullata, l'attività RanToCompletion risultante termina nello stato. L'attività Result restituita verrà impostata su una matrice contenente tutti i risultati delle attività fornite nello stesso ordine specificato, ad esempio se la matrice di attività di input contiene t1, t2, t3, l'attività Result di output restituirà un dove TResult[]arr[0] == t1.Result, arr[1] == t2.Result, and arr[2] == t3.Result).

Se la matrice/enumerabile fornita non contiene attività, l'attività restituita passerà immediatamente a uno RanToCompletion stato prima di tornare al chiamante. Il restituito TResult[] sarà una matrice di 0 elementi.

Si applica a