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

정의

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

오버로드

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

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

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

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

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

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

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

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

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

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

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

매개 변수

tasks
IEnumerable<Task>

완료를 기다리는 작업입니다.The tasks to wait on for completion.

반환

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

예외

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 작업 faulted가 있는지 여부를 결정 하는 속성입니다.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[]) WhenAll(Task[]) WhenAll(Task[]) WhenAll(Task[])

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

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

매개 변수

tasks
Task[]

완료를 기다리는 작업입니다.The tasks to wait on for completion.

반환

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

예외

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 작업 faulted가 있는지 여부를 결정 하는 속성입니다.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>>) WhenAll<TResult>(IEnumerable<Task<TResult>>) WhenAll<TResult>(IEnumerable<Task<TResult>>) WhenAll<TResult>(IEnumerable<Task<TResult>>)

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

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

형식 매개 변수

TResult

완료된 작업의 형식입니다.The type of the completed task.

매개 변수

tasks
IEnumerable<Task<TResult>>

완료를 기다리는 작업입니다.The tasks to wait on for completion.

반환

Task<TResult[]>

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

예외

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

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

예제

다음 예제에서는 1에서 1,000 사이의 임의의 숫자 1, 000을 만들고 해당 평균을 계산 하는 난수 생성기를 인스턴스화하고 각각 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>[]) WhenAll<TResult>(Task<TResult>[]) WhenAll<TResult>(Task<TResult>[]) WhenAll<TResult>(Task<TResult>[])

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

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

형식 매개 변수

TResult

완료된 작업의 형식입니다.The type of the completed task.

매개 변수

tasks
Task<TResult>[]

완료를 기다리는 작업입니다.The tasks to wait on for completion.

반환

Task<TResult[]>

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

예외

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

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

예제

다음 예제에서는 1에서 1,000 사이의 임의의 숫자 1, 000을 만들고 해당 평균을 계산 하는 난수 생성기를 인스턴스화하고 각각 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.

적용 대상