Task.WhenAll 메서드

정의

제공된 작업을 모두 완료했을 때 완료할 작업을 만듭니다.Creates a task that will complete when all of the supplied tasks have completed.

오버로드

WhenAll(IEnumerable<Task>)

열거 가능한 컬렉션의 모든 Task 개체가 완료되면 완료될 작업을 만듭니다.Creates a task that will complete when all of the Task objects in an enumerable collection have completed.

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

열거 가능한 컬렉션의 모든 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>[])

배열의 모든 Task<TResult> 개체가 완료되면 완료될 작업을 만듭니다.Creates a task that will complete when all of the Task<TResult> objects in an array have completed.

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.

반환

Task

제공된 모든 작업의 완료를 나타내는 작업입니다.A task that represents the completion of all of the supplied tasks.

예외

tasks 인수가 null인 경우The tasks argument was null.

null 작업이 포함된 tasks 컬렉션입니다.The tasks collection 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 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 일반적으로 작업 집합 또는 작업 집합에서 throw 되는 예외에 대 한 상태에 관심이 있을 때 호출 됩니다.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 , 해당 예외에는 제공 된 각 작업에서 래핑 되지 않은 예외 집합의 집계가 포함 됩니다.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.

제공 된 모든 작업에 오류가 발생 하지 않았지만 그 중 하나 이상이 취소 된 경우 반환 된 작업이 상태로 종료 됩니다 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[])

배열의 모든 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.

반환

Task

제공된 모든 작업의 완료를 나타내는 작업입니다.A task that represents the completion of all of the supplied tasks.

예외

tasks 인수가 null인 경우The tasks argument was null.

null 작업이 포함된 tasks 배열입니다.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 일반적으로 작업 집합 또는 작업 집합에서 throw 되는 예외에 대 한 상태에 관심이 있을 때 호출 됩니다.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 , 해당 예외에는 제공 된 각 작업에서 래핑 되지 않은 예외 집합의 집계가 포함 됩니다.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.

제공 된 모든 작업에 오류가 발생 하지 않았지만 그 중 하나 이상이 취소 된 경우 반환 된 작업이 상태로 종료 됩니다 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>>)

열거 가능한 컬렉션의 모든 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.

예외

tasks 인수가 null인 경우The tasks argument was null.

null 작업이 포함된 tasks 컬렉션입니다.The tasks collection contained a null task.

예제

다음 예제에서는 각각 1과 1000 사이의 1000 난수를 생성 하 고 평균을 계산 하는 난수 생성기를 인스턴스화하는 10 개의 작업을 만듭니다.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 , 해당 예외에는 제공 된 각 작업에서 래핑 되지 않은 예외 집합의 집계가 포함 됩니다.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.

제공 된 모든 작업에 오류가 발생 하지 않았지만 그 중 하나 이상이 취소 된 경우 반환 된 작업이 상태로 종료 됩니다 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>.Result 속성은 위치를 반환 합니다. TResult[] 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>[])

배열의 모든 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.

예외

tasks 인수가 null인 경우The tasks argument was null.

null 작업이 포함된 tasks 배열입니다.The tasks array contained a null task.

예제

다음 예제에서는 각각 1과 1000 사이의 1000 난수를 생성 하 고 평균을 계산 하는 난수 생성기를 인스턴스화하는 10 개의 작업을 만듭니다.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 , 해당 예외에는 제공 된 각 작업에서 래핑 되지 않은 예외 집합의 집계가 포함 됩니다.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.

제공 된 모든 작업에 오류가 발생 하지 않았지만 그 중 하나 이상이 취소 된 경우 반환 된 작업이 상태로 종료 됩니다 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[] 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.

적용 대상