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

定义

将在线程池上运行的指定工作排队,并返回该工作的任务或 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

返回

表示在线程池执行的队列的任务。A task that represents the work queued to execute in the ThreadPool.

异常

action 参数是 nullThe 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

下面的示例是类似于前一个,只不过它使用 lambda 表达式定义的任务是执行的代码。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:

有关处理由任务操作引发的异常的信息,请参阅异常处理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 参数是 nullThe function parameter was null.

注解

有关处理由任务操作引发的异常的信息,请参阅异常处理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 参数是 nullThe action parameter was null.

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. Lambda 表达式调用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方法会抛出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状态,则引发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:

有关处理由任务操作引发的异常的信息,请参阅异常处理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 参数是 nullThe function parameter was null.

cancellationToken 关联的 CancellationTokenSource 已释放。The CancellationTokenSource associated with cancellationToken was disposed.

注解

有关处理由任务操作引发的异常的信息,请参阅异常处理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 参数为 nullThe function parameter is null.

cancellationToken 关联的 CancellationTokenSource 已释放。The CancellationTokenSource associated with cancellationToken was disposed.

示例

以下示例创建 20 个会循环播放,直到一个计数器增加至 2 百万个值的任务。The following example creates 20 tasks that will loop until a counter is incremented to a value of 2 million. 前 10 个任务进入 2 百万,取消标记被取消,并其计数器未达到 200 万个任何任务被取消。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. 下面的示例是第一个,类似,只不过任务后取消了令牌,则返回前者需要已完成而不是引发异常的迭代数。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异常,因为请求取消时未启动任何任务仍会引发异常。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状态,则引发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:

有关处理由任务操作引发的异常的信息,请参阅异常处理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) 的代理的 functionA Task(TResult) that represents a proxy for the Task(TResult) returned by function.

异常

function 参数是 nullThe function parameter was null.

cancellationToken 关联的 CancellationTokenSource 已释放。The CancellationTokenSource associated with cancellationToken was disposed.

注解

有关处理由任务操作引发的异常的信息,请参阅异常处理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) 的代理的 functionA Task(TResult) that represents a proxy for the Task(TResult) returned by function.

异常

function 参数是 nullThe function parameter was null.

注解

有关处理由任务操作引发的异常的信息,请参阅异常处理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 参数为 nullThe 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+匹配零个、 一个或多个标点字符后跟一个或多个空白字符。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:

有关处理由任务操作引发的异常的信息,请参阅异常处理For information on handling exceptions thrown by task operations, see Exception Handling.

另请参阅

适用于