Task.Run Task.Run Task.Run Task.Run Method

정의

지정한 작업을 ThreadPool에서 실행하도록 큐에 대기시키고 해당 작업에 대한 작업 또는 Task<TResult> 핸들을 반환합니다.Queues the specified work to run on the ThreadPool and returns a task or Task<TResult> handle for that work.

오버로드

Run(Action) Run(Action) Run(Action)

지정한 작업을 스레드 풀에서 실행하도록 큐에 대기시키고 작업을 나타내는 Task 개체를 반환합니다.Queues the specified work to run on the thread pool and returns a Task object that represents that work.

Run(Func<Task>) Run(Func<Task>) Run(Func<Task>) Run(Func<Task>)

지정한 작업을 스레드 풀에서 실행하도록 큐에 대기시키고 function에서 반환된 작업에 대한 프록시를 반환합니다.Queues the specified work to run on the thread pool and returns a proxy for the task returned by function.

Run(Action, CancellationToken) Run(Action, CancellationToken) Run(Action, CancellationToken)

지정한 작업을 스레드 풀에서 실행하도록 큐에 대기시키고 작업을 나타내는 Task 개체를 반환합니다.Queues the specified work to run on the thread pool and returns a Task object that represents that work. 취소 토큰으로 작업을 취소할 수 있습니다.A cancellation token allows the work to be cancelled.

Run(Func<Task>, CancellationToken) Run(Func<Task>, CancellationToken) Run(Func<Task>, CancellationToken)

지정한 작업을 스레드 풀에서 실행하도록 큐에 대기시키고 function에서 반환된 작업에 대한 프록시를 반환합니다.Queues the specified work to run on the thread pool and returns a proxy for the task returned by function.

Run<TResult>(Func<TResult>, CancellationToken) Run<TResult>(Func<TResult>, CancellationToken) Run<TResult>(Func<TResult>, CancellationToken)

지정한 작업을 스레드 풀에서 실행하도록 큐에 대기시키고 작업을 나타내는 Task(TResult) 개체를 반환합니다.Queues the specified work to run on the thread pool and returns a Task(TResult) object that represents that work. 취소 토큰으로 작업을 취소할 수 있습니다.A cancellation token allows the work to be cancelled.

Run<TResult>(Func<Task<TResult>>, CancellationToken) Run<TResult>(Func<Task<TResult>>, CancellationToken) Run<TResult>(Func<Task<TResult>>, CancellationToken)

지정된 작업을 스레드 풀에서 실행하도록 큐에 대기시키고 function에서 반환된 Task(TResult)에 대한 프록시를 반환합니다.Queues the specified work to run on the thread pool and returns a proxy for the Task(TResult) returned by function.

Run<TResult>(Func<Task<TResult>>) Run<TResult>(Func<Task<TResult>>) Run<TResult>(Func<Task<TResult>>) Run<TResult>(Func<Task<TResult>>)

지정된 작업을 스레드 풀에서 실행하도록 큐에 대기시키고 function에서 반환된 Task(TResult)에 대한 프록시를 반환합니다.Queues the specified work to run on the thread pool and returns a proxy for the Task(TResult) returned by function.

Run<TResult>(Func<TResult>) Run<TResult>(Func<TResult>) Run<TResult>(Func<TResult>) Run<TResult>(Func<TResult>)

지정한 작업을 스레드 풀에서 실행하도록 큐에 대기시키고 작업을 나타내는 Task<TResult> 개체를 반환합니다.Queues the specified work to run on the thread pool and returns a Task<TResult> object that represents that work.

설명

Run 메서드 쉽게 기본값을 사용 하 여 작업을 시작 하는 오버 로드 집합을 제공 합니다.The Run method provides a set of overloads that make it easy to start a task by using default values. 경량 대체 하는 것은 StartNew 오버 로드 합니다.It is a lightweight alternative to the StartNew overloads.

Run(Action) Run(Action) Run(Action)

지정한 작업을 스레드 풀에서 실행하도록 큐에 대기시키고 작업을 나타내는 Task 개체를 반환합니다.Queues the specified work to run on the thread pool and returns a Task object that represents that work.

public:
 static System::Threading::Tasks::Task ^ Run(Action ^ action);
public static System.Threading.Tasks.Task Run (Action action);
static member Run : Action -> System.Threading.Tasks.Task

매개 변수

action
Action Action Action Action

비동기적으로 실행할 작업입니다.The work to execute asynchronously

반환

스레드 풀에서 실행하도록 큐에 대기된 작업(work)을 나타내는 작업(task)입니다.A task that represents the work queued to execute in the ThreadPool.

예외

action 매개 변수가 null입니다.The action parameter was null.

예제

다음 예제에서는 정의 ShowThreadInfo 표시 하는 메서드는 Thread.ManagedThreadId 현재 스레드의 합니다.The following example defines a ShowThreadInfo method that displays the Thread.ManagedThreadId of the current thread. 애플리케이션 스레드에서 직접 호출 하 고에서 호출 되는 Action 전달 된 대리자는 Run(Action) 메서드.It is called directly from the application thread, and is called from the Action delegate passed to the Run(Action) method.

using System;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      ShowThreadInfo("Application");

      var t = Task.Run(() => ShowThreadInfo("Task") );
      t.Wait();
   }

   static void ShowThreadInfo(String s)
   {
      Console.WriteLine("{0} Thread ID: {1}",
                        s, Thread.CurrentThread.ManagedThreadId);
   }
}
// The example displays the following output:
//       Application thread ID: 1
//       Task thread ID: 3
Imports System.Threading
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      ShowThreadInfo("Application")

      Dim t As Task = Task.Run(Sub() ShowThreadInfo("Task") )
      t.Wait()
   End Sub
   
   Private Sub ShowThreadInfo(s As String)
      Console.WriteLine("{0} Thread ID: {1}",
                        s, Thread.CurrentThread.ManagedThreadId)
   End Sub
End Module
' The example displays output like the following:
'    Application thread ID: 1
'    Task thread ID: 3

다음 예제에서는 태스크를 실행 하는 코드를 정의 하는 람다 식을 사용 하 여 이전와 비슷합니다.The following example is similar to the previous one, except that it uses a lambda expression to define the code that the task is to execute.

using System;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      Console.WriteLine("Application thread ID: {0}",
                        Thread.CurrentThread.ManagedThreadId);
      var t = Task.Run(() => {  Console.WriteLine("Task thread ID: {0}",
                                   Thread.CurrentThread.ManagedThreadId);
                             } );
      t.Wait();
   }
}
// The example displays the following output:
//       Application thread ID: 1
//       Task thread ID: 3
Imports System.Threading
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Console.WriteLine("Application thread ID: {0}",
                        Thread.CurrentThread.ManagedThreadId)
      Dim t As Task = Task.Run(Sub()
                                  Console.WriteLine("Task thread ID: {0}",
                                                    Thread.CurrentThread.ManagedThreadId)
                               End Sub)
      t.Wait()
   End Sub
End Module
' The example displays output like the following:
'    Application thread ID: 1
'    Task thread ID: 3

예제에서는 기본 애플리케이션 스레드가 아닌 다른 스레드에서 비동기 작업 실행을 보여 줍니다.The examples show that the asynchronous task executes on a different thread than the main application thread.

에 대 한 호출을 Wait 메서드를 사용 하면 태스크를 완료 하는 애플리케이션 종료 되기 전에 해당 출력을 표시 합니다.The call to the Wait method ensures that the task completes and displays its output before the application ends. 그렇지 않을 경우 가능한는 Main 메서드는 작업이 완료 되기 전에 완료 됩니다.Otherwise, it is possible that the Main method will complete before the task finishes.

다음 예제는 Run(Action) 메서드.The following example illustrates the Run(Action) method. 디렉터리 이름의 배열을 정의 하 고 각 디렉터리에 파일 이름을 검색 하는 별도 작업을 시작 합니다.It defines an array of directory names and starts a separate task to retrieve the file names in each directory. 모든 작업을 단일 파일 이름을 쓸 ConcurrentBag<T> 개체입니다.All tasks write the file names to a single ConcurrentBag<T> object. 다음 호출 하 여 합니다 WaitAll(Task[]) 모든 작업을 완료 하 고 다음에 기록 하는 파일 이름의 총 개수를 표시 하도록 메서드를 ConcurrentBag<T> 개체입니다.The example then calls the WaitAll(Task[]) method to ensure that all tasks have completed, and then displays a count of the total number of file names written to the ConcurrentBag<T> object.

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      var list = new ConcurrentBag<string>();
      string[] dirNames = { ".", ".." };
      List<Task> tasks = new List<Task>();
      foreach (var dirName in dirNames) {
         Task t = Task.Run( () => { foreach(var path in Directory.GetFiles(dirName)) 
                                       list.Add(path); }  );
         tasks.Add(t);
      }
      Task.WaitAll(tasks.ToArray());
      foreach (Task t in tasks)
         Console.WriteLine("Task {0} Status: {1}", t.Id, t.Status);
         
      Console.WriteLine("Number of files read: {0}", list.Count);
   }
}
// The example displays output like the following:
//       Task 1 Status: RanToCompletion
//       Task 2 Status: RanToCompletion
//       Number of files read: 23
Imports System.Collections.Concurrent
Imports System.Collections.Generic
Imports System.IO
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Dim list As New ConcurrentBag(Of String)()
      Dim dirNames() As String = { ".", ".." }
      Dim tasks As New List(Of Task)()
      For Each dirName In dirNames 
         Dim t As Task = Task.Run( Sub()
                                      For Each path In Directory.GetFiles(dirName) 
                                         list.Add(path)
                                      Next
                                   End Sub  )
         tasks.Add(t)
      Next
      Task.WaitAll(tasks.ToArray())
      For Each t In tasks
         Console.WriteLine("Task {0} Status: {1}", t.Id, t.Status)
      Next   
      Console.WriteLine("Number of files read: {0}", list.Count)
   End Sub
End Module
' The example displays output like the following:
'       Task 1 Status: RanToCompletion
'       Task 2 Status: RanToCompletion
'       Number of files read: 23

설명

합니다 Run 메서드를 만들고 단일 메서드 호출에서 작업을 실행 하면 이며 대안을는 StartNew 메서드.The Run method allows you to create and execute a task in a single method call and is a simpler alternative to the StartNew method. 다음과 같은 기본 값을 사용 하 여 작업을 만듭니다.It creates a task with the following default values:

작업에서 throw 된 예외 처리에 대 한 자세한 내용은 예외 처리합니다.For information on handling exceptions thrown by task operations, see Exception Handling.

추가 정보

Run(Func<Task>) Run(Func<Task>) Run(Func<Task>) Run(Func<Task>)

지정한 작업을 스레드 풀에서 실행하도록 큐에 대기시키고 function에서 반환된 작업에 대한 프록시를 반환합니다.Queues the specified work to run on the thread pool and returns a proxy for the task returned by function.

public:
 static System::Threading::Tasks::Task ^ Run(Func<System::Threading::Tasks::Task ^> ^ function);
public static System.Threading.Tasks.Task Run (Func<System.Threading.Tasks.Task> function);
static member Run : Func<System.Threading.Tasks.Task> -> System.Threading.Tasks.Task
Public Shared Function Run (function As Func(Of Task)) As Task

매개 변수

function
Func<Task>

비동기적으로 실행할 작업입니다.The work to execute asynchronously

반환

function에서 반환하는 작업에 대한 프록시를 나타내는 작업입니다.A task that represents a proxy for the task returned by function.

예외

function 매개 변수가 null입니다.The function parameter was null.

설명

작업에서 throw 된 예외 처리에 대 한 자세한 내용은 예외 처리합니다.For information on handling exceptions thrown by task operations, see Exception Handling.

추가 정보

Run(Action, CancellationToken) Run(Action, CancellationToken) Run(Action, CancellationToken)

지정한 작업을 스레드 풀에서 실행하도록 큐에 대기시키고 작업을 나타내는 Task 개체를 반환합니다.Queues the specified work to run on the thread pool and returns a Task object that represents that work. 취소 토큰으로 작업을 취소할 수 있습니다.A cancellation token allows the work to be cancelled.

public:
 static System::Threading::Tasks::Task ^ Run(Action ^ action, System::Threading::CancellationToken cancellationToken);
public static System.Threading.Tasks.Task Run (Action action, System.Threading.CancellationToken cancellationToken);
static member Run : Action * System.Threading.CancellationToken -> System.Threading.Tasks.Task

매개 변수

action
Action Action Action Action

비동기적으로 실행할 작업입니다.The work to execute asynchronously

cancellationToken
CancellationToken CancellationToken CancellationToken CancellationToken

작업을 취소하는 데 사용할 수 있는 취소 토큰입니다.A cancellation token that can be used to cancel the work

반환

스레드 풀에서 실행하도록 큐에 대기된 작업을 나타내는 작업입니다.A task that represents the work queued to execute in the thread pool.

예외

action 매개 변수가 null입니다.The action parameter was null.

작업이 취소되었습니다.The task has been canceled.

cancellationToken과 연결된 CancellationTokenSource가 삭제되었습니다.The CancellationTokenSource associated with cancellationToken was disposed.

예제

다음 예제에서는 Run(Action, CancellationToken) C:\Windows\System32 디렉터리의 파일을 반복 하는 작업을 만드는 방법.The following example calls the Run(Action, CancellationToken) method to create a task that iterates the files in the C:\Windows\System32 directory. 람다 식 호출을 Parallel.ForEach 각 파일에 대 한 정보를 추가 하는 메서드를 List<T> 개체입니다.The lambda expression calls the Parallel.ForEach method to add information about each file to a List<T> object. 중첩 된 작업을 호출 하 여 각 분리를 Parallel.ForEach 루프 취소 토큰의 상태를 확인 하 고, 취소가 요청 된 경우 호출 된 CancellationToken.ThrowIfCancellationRequested 메서드.Each detached nested task invoked by the Parallel.ForEach loop checks the state of the cancellation token and, if cancellation is requested, calls the CancellationToken.ThrowIfCancellationRequested method. 합니다 CancellationToken.ThrowIfCancellationRequested 메서드가 throw를 OperationCanceledException 에서 처리 되는 예외를 catch 호출 호출 스레드를 차단 합니다 Task.Wait 메서드.The CancellationToken.ThrowIfCancellationRequested method throws an OperationCanceledException exception that is handled in a catch block when the calling thread calls the Task.Wait method.

using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   public static async Task Main()
   {
      var tokenSource = new CancellationTokenSource();
      var token = tokenSource.Token;
      var files = new List<Tuple<string, string, long, DateTime>>();

      var t = Task.Run( () => { string dir = "C:\\Windows\\System32\\";
                                object obj = new Object();
                                if (Directory.Exists(dir)) {
                                   Parallel.ForEach(Directory.GetFiles(dir),
                                   f => {
                                           if (token.IsCancellationRequested)
                                              token.ThrowIfCancellationRequested();
                                           var fi = new FileInfo(f);
                                           lock(obj) {
                                              files.Add(Tuple.Create(fi.Name, fi.DirectoryName, fi.Length, fi.LastWriteTimeUtc));          
                                           }
                                      });
                                 }
                              }
                        , token);
      await Task.Yield();
      tokenSource.Cancel();
      try {
         await t;
         Console.WriteLine("Retrieved information for {0} files.", files.Count);
      }
      catch (AggregateException e) {
         Console.WriteLine("Exception messages:");
         foreach (var ie in e.InnerExceptions)
            Console.WriteLine("   {0}: {1}", ie.GetType().Name, ie.Message);

         Console.WriteLine("\nTask status: {0}", t.Status);       
      }
      finally {
         tokenSource.Dispose();
      }
   }
}
// The example displays the following output:
//       Exception messages:
//          TaskCanceledException: A task was canceled.
//          TaskCanceledException: A task was canceled.
//          ...
//       
//       Task status: Canceled
Imports System.Collections.Generic
Imports System.IO
Imports System.Threading
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Dim tokenSource As New CancellationTokenSource()
      Dim token As CancellationToken = tokenSource.Token
      Dim files As New List(Of Tuple(Of String, String, Long, Date))()

      Dim t As Task = Task.Run( Sub()
                                   Dim dir As String = "C:\Windows\System32\"
                                   Dim obj As New Object()
                                   If Directory.Exists(dir)Then
                                      Parallel.ForEach(Directory.GetFiles(dir), 
                                         Sub(f)
                                            If token.IsCancellationRequested Then
                                               token.ThrowIfCancellationRequested()
                                            End If  
                                            Dim fi As New FileInfo(f)
                                            SyncLock(obj)
                                              files.Add(Tuple.Create(fi.Name, fi.DirectoryName, fi.Length, fi.LastWriteTimeUtc))          
                                            End SyncLock
                                         End Sub)
                                   End If
                                End Sub, token)
      tokenSource.Cancel()
      Try
         t.Wait() 
         Console.WriteLine("Retrieved information for {0} files.", files.Count)
      Catch e As AggregateException
         Console.WriteLine("Exception messages:")
         For Each ie As Exception In e.InnerExceptions
            Console.WriteLine("   {0}:{1}", ie.GetType().Name, ie.Message)
         Next
         Console.WriteLine()
         Console.WriteLine("Task status: {0}", t.Status)       
      Finally
         tokenSource.Dispose()
      End Try
   End Sub
End Module
' The example displays the following output:
'       Exception messages:
'          TaskCanceledException: A task was canceled.
'       
'       Task status: Canceled

설명

태스크 실행 전에 취소가 요청 될 경우 작업이 실행 되지 않습니다.If cancellation is requested before the task begins execution, the task does not execute. 로 설정 하는 대신 합니다 Canceled 상태 및 throw를 TaskCanceledException 예외입니다.Instead it is set to the Canceled state and throws a TaskCanceledException exception.

합니다 Run(Action, CancellationToken) 메서드는 대안을는 TaskFactory.StartNew(Action, CancellationToken) 메서드.The Run(Action, CancellationToken) method is a simpler alternative to the TaskFactory.StartNew(Action, CancellationToken) method. 다음과 같은 기본 값을 사용 하 여 작업을 만듭니다.It creates a task with the following default values:

작업에서 throw 된 예외 처리에 대 한 자세한 내용은 예외 처리합니다.For information on handling exceptions thrown by task operations, see Exception Handling.

추가 정보

Run(Func<Task>, CancellationToken) Run(Func<Task>, CancellationToken) Run(Func<Task>, CancellationToken)

지정한 작업을 스레드 풀에서 실행하도록 큐에 대기시키고 function에서 반환된 작업에 대한 프록시를 반환합니다.Queues the specified work to run on the thread pool and returns a proxy for the task returned by function.

public:
 static System::Threading::Tasks::Task ^ Run(Func<System::Threading::Tasks::Task ^> ^ function, System::Threading::CancellationToken cancellationToken);
public static System.Threading.Tasks.Task Run (Func<System.Threading.Tasks.Task> function, System.Threading.CancellationToken cancellationToken);
static member Run : Func<System.Threading.Tasks.Task> * System.Threading.CancellationToken -> System.Threading.Tasks.Task

매개 변수

function
Func<Task>

비동기적으로 실행할 작업입니다.The work to execute asynchronously.

cancellationToken
CancellationToken CancellationToken CancellationToken CancellationToken

작업을 취소하는 데 사용해야 하는 취소 토큰입니다.A cancellation token that should be used to cancel the work.

반환

function에서 반환하는 작업에 대한 프록시를 나타내는 작업입니다.A task that represents a proxy for the task returned by function.

예외

function 매개 변수가 null입니다.The function parameter was null.

작업이 취소되었습니다.The task has been canceled.

cancellationToken과 연결된 CancellationTokenSource가 삭제되었습니다.The CancellationTokenSource associated with cancellationToken was disposed.

설명

작업에서 throw 된 예외 처리에 대 한 자세한 내용은 예외 처리합니다.For information on handling exceptions thrown by task operations, see Exception Handling.

추가 정보

Run<TResult>(Func<TResult>, CancellationToken) Run<TResult>(Func<TResult>, CancellationToken) Run<TResult>(Func<TResult>, CancellationToken)

지정한 작업을 스레드 풀에서 실행하도록 큐에 대기시키고 작업을 나타내는 Task(TResult) 개체를 반환합니다.Queues the specified work to run on the thread pool and returns a Task(TResult) object that represents that work. 취소 토큰으로 작업을 취소할 수 있습니다.A cancellation token allows the work to be cancelled.

public:
generic <typename TResult>
 static System::Threading::Tasks::Task<TResult> ^ Run(Func<TResult> ^ function, System::Threading::CancellationToken cancellationToken);
public static System.Threading.Tasks.Task<TResult> Run<TResult> (Func<TResult> function, System.Threading.CancellationToken cancellationToken);
static member Run : Func<'Result> * System.Threading.CancellationToken -> System.Threading.Tasks.Task<'Result>

형식 매개 변수

TResult

작업의 결과 형식입니다.The result type of the task.

매개 변수

function
Func<TResult> Func<TResult> Func<TResult> Func<TResult>

비동기적으로 실행할 작업입니다.The work to execute asynchronously

cancellationToken
CancellationToken CancellationToken CancellationToken CancellationToken

작업을 취소하는 데 사용해야 하는 취소 토큰입니다.A cancellation token that should be used to cancel the work

반환

스레드 풀에서 실행하도록 큐에 대기된 작업을 나타내는 Task(TResult)입니다.A Task(TResult) that represents the work queued to execute in the thread pool.

예외

function 매개 변수가 null인 경우The function parameter is null.

작업이 취소되었습니다.The task has been canceled.

cancellationToken과 연결된 CancellationTokenSource가 삭제되었습니다.The CancellationTokenSource associated with cancellationToken was disposed.

예제

다음 예제에서는 2 백만로 카운터가 증가 될 때까지 반복 하는 20 개의 작업을 만듭니다.The following example creates 20 tasks that will loop until a counter is incremented to a value of 2 million. 처음 10 개의 작업에 도달 하면 2 백만, 취소 토큰이 취소 되 고 해당 카운터 2 백만 도달 하지 하는 모든 작업이 취소 됩니다.When the first 10 tasks reach 2 million, the cancellation token is cancelled, and any tasks whose counters have not reached 2 million are cancelled. 출력을 보여 줍니다.The example shows possible output.

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      var tasks = new List<Task<int>>();
      var source = new CancellationTokenSource();
      var token = source.Token;
      int completedIterations = 0;

      for (int n = 0; n <= 19; n++)
         tasks.Add(Task.Run( () => { int iterations = 0;
                                     for (int ctr = 1; ctr <= 2000000; ctr++) {
                                         token.ThrowIfCancellationRequested();
                                         iterations++;
                                     }
                                     Interlocked.Increment(ref completedIterations);
                                     if (completedIterations >= 10)
                                        source.Cancel();
                                     return iterations; }, token));

      Console.WriteLine("Waiting for the first 10 tasks to complete...\n");
      try  {
         Task.WaitAll(tasks.ToArray());
      }
      catch (AggregateException) {
         Console.WriteLine("Status of tasks:\n");
         Console.WriteLine("{0,10} {1,20} {2,14:N0}", "Task Id",
                           "Status", "Iterations");
         foreach (var t in tasks)
            Console.WriteLine("{0,10} {1,20} {2,14}",
                              t.Id, t.Status,
                              t.Status != TaskStatus.Canceled ? t.Result.ToString("N0") : "n/a");
      }
   }
}
// The example displays output like the following:
//    Waiting for the first 10 tasks to complete...
//    Status of tasks:
//
//       Task Id               Status     Iterations
//             1      RanToCompletion      2,000,000
//             2      RanToCompletion      2,000,000
//             3      RanToCompletion      2,000,000
//             4      RanToCompletion      2,000,000
//             5      RanToCompletion      2,000,000
//             6      RanToCompletion      2,000,000
//             7      RanToCompletion      2,000,000
//             8      RanToCompletion      2,000,000
//             9      RanToCompletion      2,000,000
//            10             Canceled            n/a
//            11             Canceled            n/a
//            12             Canceled            n/a
//            13             Canceled            n/a
//            14             Canceled            n/a
//            15             Canceled            n/a
//            16      RanToCompletion      2,000,000
//            17             Canceled            n/a
//            18             Canceled            n/a
//            19             Canceled            n/a
//            20             Canceled            n/a
Imports System.Collections.Generic
Imports System.Threading
Imports System.Threading.Tasks

Module Example

   Public Sub Main()
      Dim tasks As New List(Of Task(Of Integer))()
      Dim source As New CancellationTokenSource
      Dim token As CancellationToken = source.Token
      Dim completedIterations As Integer = 0
      
      For n As Integer = 0 To 19
         tasks.Add(Task.Run( Function()
                                Dim iterations As Integer= 0
                                For ctr As Long = 1 To 2000000
                                   token.ThrowIfCancellationRequested()
                                   iterations += 1
                                Next
                                Interlocked.Increment(completedIterations)
                                If completedIterations >= 10 Then source.Cancel()
                                Return iterations
                             End Function, token))
      Next

      Console.WriteLine("Waiting for the first 10 tasks to complete... ")
      Try
         Task.WaitAll(tasks.ToArray())
      Catch e As AggregateException
         Console.WriteLine("Status of tasks:")
         Console.WriteLine()
         Console.WriteLine("{0,10} {1,20} {2,14}", "Task Id",
                           "Status", "Iterations")
         For Each t In tasks
            Console.WriteLine("{0,10} {1,20} {2,14}",
                              t.Id, t.Status,
                              If(t.Status <> TaskStatus.Canceled,
                                 t.Result.ToString("N0"), "n/a"))
         Next
      End Try
   End Sub
End Module
' The example displays output like the following:
'    Waiting for the first 10 tasks to complete...
'    Status of tasks:
'
'       Task Id               Status     Iterations
'             1      RanToCompletion      2,000,000
'             2      RanToCompletion      2,000,000
'             3      RanToCompletion      2,000,000
'             4      RanToCompletion      2,000,000
'             5      RanToCompletion      2,000,000
'             6      RanToCompletion      2,000,000
'             7      RanToCompletion      2,000,000
'             8      RanToCompletion      2,000,000
'             9      RanToCompletion      2,000,000
'            10             Canceled            n/a
'            11             Canceled            n/a
'            12             Canceled            n/a
'            13             Canceled            n/a
'            14             Canceled            n/a
'            15             Canceled            n/a
'            16      RanToCompletion      2,000,000
'            17             Canceled            n/a
'            18             Canceled            n/a
'            19             Canceled            n/a
'            20             Canceled            n/a

사용 하는 대신는 InnerExceptions 예외를 검사할 속성 예제에서는 성공적으로 완료 되는 취소 되었으면 확인 하는 모든 작업을 반복 합니다.Instead of using the InnerExceptions property to examine exceptions, the example iterates all tasks to determine which have completed successfully and which have been cancelled. 완료에 대해 작업에서 반환 값을 표시 합니다.For those that have completed, it displays the value returned by the task.

취소는 협조적 이기 때문에 각 작업 취소에 응답 하는 방법을 결정할 수 있습니다.Because cancellation is cooperative, each task can decide how to respond to cancellation. 다음 예제에서는 한다는 점을 제외 하 고 작업은 완료 하지 않고 예외를 throw 하는 반복 횟수를 반환 된 토큰이 취소 되 면 첫 번째와 비슷합니다.The following example is like the first, except that, once the token is cancelled, tasks return the number of iterations they've completed rather than throw an exception.

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      var tasks = new List<Task<int>>();
      var source = new CancellationTokenSource();
      var token = source.Token;
      int completedIterations = 0;

      for (int n = 0; n <= 19; n++)
         tasks.Add(Task.Run( () => { int iterations = 0;
                                     for (int ctr = 1; ctr <= 2000000; ctr++) {
                                         if (token.IsCancellationRequested)
                                            return iterations;
                                         iterations++;
                                     }
                                     Interlocked.Increment(ref completedIterations);
                                     if (completedIterations >= 10)
                                        source.Cancel();
                                     return iterations; }, token));

      Console.WriteLine("Waiting for the first 10 tasks to complete...\n");
      try  {
         Task.WaitAll(tasks.ToArray());
      }
      catch (AggregateException) {
         Console.WriteLine("Status of tasks:\n");
         Console.WriteLine("{0,10} {1,20} {2,14:N0}", "Task Id",
                           "Status", "Iterations");
         foreach (var t in tasks)
            Console.WriteLine("{0,10} {1,20} {2,14}",
                              t.Id, t.Status,
                              t.Status != TaskStatus.Canceled ? t.Result.ToString("N0") : "n/a");
      }
   }
}
// The example displays output like the following:
//    Status of tasks:
//
//       Task Id               Status     Iterations
//             1      RanToCompletion      2,000,000
//             2      RanToCompletion      2,000,000
//             3      RanToCompletion      2,000,000
//             4      RanToCompletion      2,000,000
//             5      RanToCompletion      2,000,000
//             6      RanToCompletion      2,000,000
//             7      RanToCompletion      2,000,000
//             8      RanToCompletion      2,000,000
//             9      RanToCompletion      2,000,000
//            10      RanToCompletion      1,658,326
//            11      RanToCompletion      1,988,506
//            12      RanToCompletion      2,000,000
//            13      RanToCompletion      1,942,246
//            14      RanToCompletion        950,108
//            15      RanToCompletion      1,837,832
//            16      RanToCompletion      1,687,182
//            17      RanToCompletion        194,548
//            18             Canceled    Not Started
//            19             Canceled    Not Started
//            20             Canceled    Not Started
Imports System.Collections.Generic
Imports System.Threading
Imports System.Threading.Tasks

Module Example

   Public Sub Main()
      Dim tasks As New List(Of Task(Of Integer))()
      Dim source As New CancellationTokenSource
      Dim token As CancellationToken = source.Token
      Dim completedIterations As Integer = 0
      
      For n As Integer = 0 To 19
         tasks.Add(Task.Run( Function()
                                Dim iterations As Integer= 0
                                For ctr As Long = 1 To 2000000
                                   If token.IsCancellationRequested Then
                                      Return iterations
                                   End If
                                   iterations += 1
                                Next
                                Interlocked.Increment(completedIterations)
                                If completedIterations >= 10 Then source.Cancel()
                                Return iterations
                             End Function, token))
      Next

      Try
         Task.WaitAll(tasks.ToArray())
      Catch e As AggregateException
         Console.WriteLine("Status of tasks:")
         Console.WriteLine()
         Console.WriteLine("{0,10} {1,20} {2,14:N0}", "Task Id",
                           "Status", "Iterations")
         For Each t In tasks
            Console.WriteLine("{0,10} {1,20} {2,14}",
                              t.Id, t.Status,
                              If(t.Status <> TaskStatus.Canceled,
                                 t.Result.ToString("N0"), "Not Started"))
         Next
      End Try
   End Sub
End Module
' The example displays output like the following:
'    Status of tasks:
'
'       Task Id               Status     Iterations
'             1      RanToCompletion      2,000,000
'             2      RanToCompletion      2,000,000
'             3      RanToCompletion      2,000,000
'             4      RanToCompletion      2,000,000
'             5      RanToCompletion      2,000,000
'             6      RanToCompletion      2,000,000
'             7      RanToCompletion      2,000,000
'             8      RanToCompletion      2,000,000
'             9      RanToCompletion      2,000,000
'            10      RanToCompletion      1,658,326
'            11      RanToCompletion      1,988,506
'            12      RanToCompletion      2,000,000
'            13      RanToCompletion      1,942,246
'            14      RanToCompletion        950,108
'            15      RanToCompletion      1,837,832
'            16      RanToCompletion      1,687,182
'            17      RanToCompletion        194,548
'            18             Canceled    Not Started
'            19             Canceled    Not Started
'            20             Canceled    Not Started

이 예제에서는 여전히 처리 해야 합니다는 AggregateException 취소가 요청 될 때 시작 되지 않은 모든 작업에는 여전히 예외가 throw 되므로 예외입니다.The example still must handle the AggregateException exception, since any tasks that have not started when cancellation is requested still throw an exception.

설명

태스크 실행 전에 취소가 요청 될 경우 작업이 실행 되지 않습니다.If cancellation is requested before the task begins execution, the task does not execute. 로 설정 하는 대신 합니다 Canceled 상태 및 throw를 TaskCanceledException 예외입니다.Instead it is set to the Canceled state and throws a TaskCanceledException exception.

합니다 Run 메서드는 대안을는 StartNew 메서드.The Run method is a simpler alternative to the StartNew method. 다음과 같은 기본 값을 사용 하 여 작업을 만듭니다.It creates a task with the following default values:

작업에서 throw 된 예외 처리에 대 한 자세한 내용은 예외 처리합니다.For information on handling exceptions thrown by task operations, see Exception Handling.

추가 정보

Run<TResult>(Func<Task<TResult>>, CancellationToken) Run<TResult>(Func<Task<TResult>>, CancellationToken) Run<TResult>(Func<Task<TResult>>, CancellationToken)

지정된 작업을 스레드 풀에서 실행하도록 큐에 대기시키고 function에서 반환된 Task(TResult)에 대한 프록시를 반환합니다.Queues the specified work to run on the thread pool and returns a proxy for the Task(TResult) returned by function.

public:
generic <typename TResult>
 static System::Threading::Tasks::Task<TResult> ^ Run(Func<System::Threading::Tasks::Task<TResult> ^> ^ function, System::Threading::CancellationToken cancellationToken);
public static System.Threading.Tasks.Task<TResult> Run<TResult> (Func<System.Threading.Tasks.Task<TResult>> function, System.Threading.CancellationToken cancellationToken);
static member Run : Func<System.Threading.Tasks.Task<'Result>> * System.Threading.CancellationToken -> System.Threading.Tasks.Task<'Result>

형식 매개 변수

TResult

프록시 작업에서 반환되는 결과의 형식입니다.The type of the result returned by the proxy task.

매개 변수

function
Func<Task<TResult>>

비동기적으로 실행할 작업입니다.The work to execute asynchronously

cancellationToken
CancellationToken CancellationToken CancellationToken CancellationToken

작업을 취소하는 데 사용해야 하는 취소 토큰입니다.A cancellation token that should be used to cancel the work

반환

Task(TResult)에서 반환하는 Task(TResult)에 대한 프록시를 나타내는 function입니다.A Task(TResult) that represents a proxy for the Task(TResult) returned by function.

예외

function 매개 변수가 null입니다.The function parameter was null.

작업이 취소되었습니다.The task has been canceled.

cancellationToken과 연결된 CancellationTokenSource가 삭제되었습니다.The CancellationTokenSource associated with cancellationToken was disposed.

설명

작업에서 throw 된 예외 처리에 대 한 자세한 내용은 예외 처리합니다.For information on handling exceptions thrown by task operations, see Exception Handling.

추가 정보

Run<TResult>(Func<Task<TResult>>) Run<TResult>(Func<Task<TResult>>) Run<TResult>(Func<Task<TResult>>) Run<TResult>(Func<Task<TResult>>)

지정된 작업을 스레드 풀에서 실행하도록 큐에 대기시키고 function에서 반환된 Task(TResult)에 대한 프록시를 반환합니다.Queues the specified work to run on the thread pool and returns a proxy for the Task(TResult) returned by function.

public:
generic <typename TResult>
 static System::Threading::Tasks::Task<TResult> ^ Run(Func<System::Threading::Tasks::Task<TResult> ^> ^ function);
public static System.Threading.Tasks.Task<TResult> Run<TResult> (Func<System.Threading.Tasks.Task<TResult>> function);
static member Run : Func<System.Threading.Tasks.Task<'Result>> -> System.Threading.Tasks.Task<'Result>
Public Shared Function Run(Of TResult) (function As Func(Of Task(Of TResult))) As Task(Of TResult)

형식 매개 변수

TResult

프록시 작업에서 반환되는 결과의 형식입니다.The type of the result returned by the proxy task.

매개 변수

function
Func<Task<TResult>>

비동기적으로 실행할 작업입니다.The work to execute asynchronously

반환

Task(TResult)에서 반환하는 Task(TResult)에 대한 프록시를 나타내는 function입니다.A Task(TResult) that represents a proxy for the Task(TResult) returned by function.

예외

function 매개 변수가 null입니다.The function parameter was null.

설명

작업에서 throw 된 예외 처리에 대 한 자세한 내용은 예외 처리합니다.For information on handling exceptions thrown by task operations, see Exception Handling.

추가 정보

Run<TResult>(Func<TResult>) Run<TResult>(Func<TResult>) Run<TResult>(Func<TResult>) Run<TResult>(Func<TResult>)

지정한 작업을 스레드 풀에서 실행하도록 큐에 대기시키고 작업을 나타내는 Task<TResult> 개체를 반환합니다.Queues the specified work to run on the thread pool and returns a Task<TResult> object that represents that work.

public:
generic <typename TResult>
 static System::Threading::Tasks::Task<TResult> ^ Run(Func<TResult> ^ function);
public static System.Threading.Tasks.Task<TResult> Run<TResult> (Func<TResult> function);
static member Run : Func<'Result> -> System.Threading.Tasks.Task<'Result>
Public Shared Function Run(Of TResult) (function As Func(Of TResult)) As Task(Of TResult)

형식 매개 변수

TResult

작업의 반환 유형입니다.The return type of the task.

매개 변수

function
Func<TResult> Func<TResult> Func<TResult> Func<TResult>

비동기적으로 실행할 작업입니다.The work to execute asynchronously.

반환

스레드 풀에서 실행하도록 큐에 대기된 작업을 나타내는 작업 개체입니다.A task object that represents the work queued to execute in the thread pool.

예외

function 매개 변수가 null인 경우The function parameter is null.

예제

다음 예에서는 게시 된 책을 나타내는 텍스트 파일의 단어의 대략적인 수를 셉니다.The following example counts the approximate number of words in text files that represent published books. 각 태스크는 파일을 열고 전체 콘텐츠를 비동기적으로 읽고, 정규식을 사용 하 여 단어 수를 계산 하는 일을 담당 합니다.Each task is responsible for opening a file, reading its entire contents asynchronously, and calculating the word count by using a regular expression. WaitAll(Task[]) 메서드는 콘솔에 각 책의 단어 수를 표시 하기 전에 모든 작업 완료를 확인 합니다.The WaitAll(Task[]) method is called to ensure that all tasks have completed before displaying the word count of each book to the console.

using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      string pattern = @"\p{P}*\s+";
      string[] titles = { "Sister Carrie", "The Financier" };
      Task<int>[] tasks = new Task<int>[titles.Length];

      for (int ctr = 0; ctr < titles.Length; ctr++) {
         string s = titles[ctr];
         tasks[ctr] = Task.Run( () => {
                                   // Number of words.
                                   int nWords = 0;
                                   // Create filename from title.
                                   string fn = s + ".txt";
                                   if (File.Exists(fn)) {
                                      StreamReader sr = new StreamReader(fn);
                                      string input = sr.ReadToEndAsync().Result;
                                      nWords = Regex.Matches(input, pattern).Count;
                                   }
                                   return nWords;
                                } );
      }
      Task.WaitAll(tasks);

      Console.WriteLine("Word Counts:\n");
      for (int ctr = 0; ctr < titles.Length; ctr++)
         Console.WriteLine("{0}: {1,10:N0} words", titles[ctr], tasks[ctr].Result);
   }
}
// The example displays the following output:
//       Sister Carrie:    159,374 words
//       The Financier:    196,362 words
Imports System.IO
Imports System.Text.RegularExpressions
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Dim pattern As String = "\p{P}*\s+"
      Dim titles() As String = { "Sister Carrie",
                                 "The Financier" }
      Dim tasks(titles.Length - 1) As Task(Of Integer)

      For ctr As Integer = 0 To titles.Length - 1
         Dim s As String = titles(ctr)
         tasks(ctr) = Task.Run( Function()
                                   ' Number of words.
                                   Dim nWords As Integer = 0
                                   ' Create filename from title.
                                   Dim fn As String = s + ".txt"
                                   If File.Exists(fn) Then
                                      Dim sr As New StreamReader(fn)
                                      Dim input As String = sr.ReadToEndAsync().Result
                                      nWords = Regex.Matches(input, pattern).Count
                                   End If
                                   Return nWords
                                End Function)
      Next
      Task.WaitAll(tasks)

      Console.WriteLine("Word Counts:")
      Console.WriteLine()
      For ctr As Integer = 0 To titles.Length - 1
         Console.WriteLine("{0}: {1,10:N0} words", titles(ctr), tasks(ctr).Result)
      Next
   End Sub
End Module
' The example displays the following output:
'       Sister Carrie:    159,374 words
'       The Financier:    196,362 words

정규식 \p{P}*\s+ 0, 1 또는 뒤에 하나 이상의 공백 문자가 문장 부호 문자가 더 이상 일치 합니다.The regular expression \p{P}*\s+ matches zero, one, or more punctuation characters followed by one or more white-space characters. 일치 항목의 총 수가 대략적인 단어 수를 가정 합니다.It assumes that the total number of matches equals the approximate word count.

설명

합니다 Run 메서드는 대안을는 TaskFactory.StartNew(Action) 메서드.The Run method is a simpler alternative to the TaskFactory.StartNew(Action) method. 다음과 같은 기본 값을 사용 하 여 작업을 만듭니다.It creates a task with the following default values:

작업에서 throw 된 예외 처리에 대 한 자세한 내용은 예외 처리합니다.For information on handling exceptions thrown by task operations, see Exception Handling.

추가 정보

적용 대상