Task 类

定义

表示一个异步操作。Represents an asynchronous operation.

public ref class Task : IAsyncResult, IDisposable
public class Task : IAsyncResult, IDisposable
type Task = class
    interface IAsyncResult
    interface IDisposable
Public Class Task
Implements IAsyncResult, IDisposable
继承
Task
派生
实现

注解

Task 类表示不返回值并且通常以异步方式执行的单个操作。The Task class represents a single operation that does not return a value and that usually executes asynchronously. Task 对象是第一次在 .NET Framework 4 中引入的基于任务的异步模式的中心组件之一。Task objects are one of the central components of the task-based asynchronous pattern first introduced in the .NET Framework 4. 由于 Task 对象执行的工作通常在线程池线程上异步执行,而不是在主应用程序线程上同步执行,因此您可以使用 Status 属性,还可以使用 IsCanceledIsCompletedIsFaulted 属性,用于确定任务的状态。Because the work performed by a Task object typically executes asynchronously on a thread pool thread rather than synchronously on the main application thread, you can use the Status property, as well as the IsCanceled, IsCompleted, and IsFaulted properties, to determine the state of a task. 通常,lambda 表达式用于指定任务要执行的工作。Most commonly, a lambda expression is used to specify the work that the task is to perform.

对于返回值的操作,请使用 Task<TResult> 类。For operations that return values, you use the Task<TResult> class.

本节内容:In this section:

任务实例化示例 Task instantiation examples
创建和执行任务 Creating and executing a task
分离任务创建和执行 Separating task creation and execution
正在等待一个或多个任务完成 Waiting for one or more tasks to complete
任务和区域性 Tasks and culture
对于调试器开发人员For debugger developers

任务实例化Task instantiation

下面的示例创建并执行四个任务。The following example creates and executes four tasks. 三个任务执行一个名为 actionAction<T> 委托,该委托接受 Object类型的参数。Three tasks execute an Action<T> delegate named action, which accepts an argument of type Object. 第四个任务执行在对任务创建方法的调用中以内联方式定义的 lambda 表达式(Action 委托)。A fourth task executes a lambda expression (an Action delegate) that is defined inline in the call to the task creation method. 每个任务实例化并以不同的方式运行:Each task is instantiated and run in a different way:

  • 任务 t1 通过调用任务类构造函数进行实例化,但只有在启动任务 t2 之后,才通过调用其 Start() 方法来启动。Task t1 is instantiated by calling a Task class constructor, but is started by calling its Start() method only after task t2 has started.

  • 通过调用 TaskFactory.StartNew(Action<Object>, Object) 方法在单个方法调用中实例化和启动任务 t2Task t2 is instantiated and started in a single method call by calling the TaskFactory.StartNew(Action<Object>, Object) method.

  • 通过调用 Run(Action) 方法在单个方法调用中实例化和启动任务 t3Task t3 is instantiated and started in a single method call by calling the Run(Action) method.

  • 通过调用 RunSynchronously() 方法,在主线程上同步执行任务 t4Task t4 is executed synchronously on the main thread by calling the RunSynchronously() method.

由于 task t4 同步执行,因此它在主应用程序线程上执行。Because task t4 executes synchronously, it executes on the main application thread. 其余任务通常在一个或多个线程池线程上异步执行。The remaining tasks execute asynchronously typically on one or more thread pool threads.

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

class Example
{
    static void Main()
    {
        Action<object> action = (object obj) =>
                                {
                                   Console.WriteLine("Task={0}, obj={1}, Thread={2}",
                                   Task.CurrentId, obj,
                                   Thread.CurrentThread.ManagedThreadId);
                                };

        // Create a task but do not start it.
        Task t1 = new Task(action, "alpha");

        // Construct a started task
        Task t2 = Task.Factory.StartNew(action, "beta");
        // Block the main thread to demonstrate that t2 is executing
        t2.Wait();

        // Launch t1 
        t1.Start();
        Console.WriteLine("t1 has been launched. (Main Thread={0})",
                          Thread.CurrentThread.ManagedThreadId);
        // Wait for the task to finish.
        t1.Wait();

        // Construct a started task using Task.Run.
        String taskData = "delta";
        Task t3 = Task.Run( () => {Console.WriteLine("Task={0}, obj={1}, Thread={2}",
                                                     Task.CurrentId, taskData,
                                                      Thread.CurrentThread.ManagedThreadId);
                                   });
        // Wait for the task to finish.
        t3.Wait();

        // Construct an unstarted task
        Task t4 = new Task(action, "gamma");
        // Run it synchronously
        t4.RunSynchronously();
        // Although the task was run synchronously, it is a good practice
        // to wait for it in the event exceptions were thrown by the task.
        t4.Wait();
    }
}
// The example displays output like the following:
//       Task=1, obj=beta, Thread=3
//       t1 has been launched. (Main Thread=1)
//       Task=2, obj=alpha, Thread=4
//       Task=3, obj=delta, Thread=3
//       Task=4, obj=gamma, Thread=1
Imports System.Threading
Imports System.Threading.Tasks

Module Example
    Public Sub Main()
        Dim action As Action(Of Object) = 
              Sub(obj As Object)
                 Console.WriteLine("Task={0}, obj={1}, Thread={2}", 
                 Task.CurrentId, obj,
                 Thread.CurrentThread.ManagedThreadId)
              End Sub

        ' Construct an unstarted task
        Dim t1 As New Task(action, "alpha")

        ' Construct a started task
        Dim t2 As Task = Task.Factory.StartNew(action, "beta")
        ' Block the main thread to demonstrate that t2 is executing
        t2.Wait()

        ' Launch t1 
        t1.Start()
        Console.WriteLine("t1 has been launched. (Main Thread={0})",
                          Thread.CurrentThread.ManagedThreadId)
        ' Wait for the task to finish.
        t1.Wait()

        ' Construct a started task using Task.Run.
        Dim taskData As String = "delta"
        Dim t3 As Task = Task.Run(Sub()
                                     Console.WriteLine("Task={0}, obj={1}, Thread={2}",
                                     Task.CurrentId, taskData,
                                     Thread.CurrentThread.ManagedThreadId)
                                  End Sub)
        ' Wait for the task to finish.
        t3.Wait()
        
        ' Construct an unstarted task
        Dim t4 As New Task(action, "gamma")
        ' Run it synchronously
        t4.RunSynchronously()
        ' Although the task was run synchronously, it is a good practice
        ' to wait for it in the event exceptions were thrown by the task.
        t4.Wait()
    End Sub
End Module
' The example displays output like the following:
'       Task=1, obj=beta, Thread=3
'       t1 has been launched. (Main Thread=1)
'       Task=2, obj=alpha, Thread=3
'       Task=3, obj=delta, Thread=3
'       Task=4, obj=gamma, Thread=1

创建和执行任务Creating and executing a task

可以通过多种方式创建 Task 实例。Task instances may be created in a variety of ways. 最常见的方法(从 .NET Framework 4.5.NET Framework 4.5开始提供)是调用静态 Run 方法。The most common approach, which is available starting with the .NET Framework 4.5.NET Framework 4.5, is to call the static Run method. Run 方法提供一种简单的方法来使用默认值启动任务,而无需其他参数。The Run method provides a simple way to start a task using default values and without requiring additional parameters. 下面的示例使用 Run(Action) 方法来启动任务,该任务将循环,并显示循环迭代次数:The following example uses the Run(Action) method to start a task that loops and then displays the number of loop iterations:

using System;
using System.Threading.Tasks;

public class Example
{
   public static async Task Main()
   {
      await Task.Run( () => {
                                  // Just loop.
                                  int ctr = 0;
                                  for (ctr = 0; ctr <= 1000000; ctr++)
                                  {}
                                  Console.WriteLine("Finished {0} loop iterations",
                                                    ctr);
                               } );
   }
}
// The example displays the following output:
//        Finished 1000001 loop iterations
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Dim t As Task = Task.Run(Sub()
                                  ' Just loop.
                                  Dim ctr As Integer = 0
                                  For ctr = 0 to 1000000
                                  Next
                                  Console.WriteLine("Finished {0} loop iterations",
                                                    ctr)
                               End Sub)
      t.Wait()
   End Sub
End Module
' The example displays the following output:
'       Finished 1000001 loop iterations

用于在 .NET Framework 4.NET Framework 4中启动任务的一种替代方法和最常见的方法是静态的 TaskFactory.StartNew 方法。An alternative, and the most common method to start a task in .NET Framework 4.NET Framework 4, is the static TaskFactory.StartNew method. Task.Factory 属性返回一个 TaskFactory 对象。The Task.Factory property returns a TaskFactory object. 使用 TaskFactory.StartNew 方法的重载,你可以指定要传递给任务创建选项和任务计划程序的参数。Overloads of the TaskFactory.StartNew method let you specify parameters to pass to the task creation options and a task scheduler. 下面的示例使用 TaskFactory.StartNew 方法来启动任务。The following example uses the TaskFactory.StartNew method to start a task. 它在功能上等效于上一示例中的代码。It is functionally equivalent to the code in the previous example.

using System;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      Task t = Task.Factory.StartNew( () => {
                                  // Just loop.
                                  int ctr = 0;
                                  for (ctr = 0; ctr <= 1000000; ctr++)
                                  {}
                                  Console.WriteLine("Finished {0} loop iterations",
                                                    ctr);
                               } );
      t.Wait();
   }
}
// The example displays the following output:
//        Finished 1000001 loop iterations
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Dim t As Task = Task.Factory.StartNew(Sub()
                                  ' Just loop.
                                  Dim ctr As Integer = 0
                                  For ctr = 0 to 1000000
                                  Next
                                  Console.WriteLine("Finished {0} loop iterations",
                                                    ctr)
                               End Sub)
      t.Wait()
   End Sub
End Module
' The example displays the following output:
'       Finished 1000001 loop iterations

有关更完整的示例,请参阅基于任务的异步编程For more complete examples, see Task-based Asynchronous Programming.

分离任务创建和执行Separating task creation and execution

Task 类还提供了初始化任务的构造函数,但不计划执行该任务。The Task class also provides constructors that initialize the task but that do not schedule it for execution. 出于性能原因,Task.RunTaskFactory.StartNew 方法是用于创建和计划计算任务的首选机制,但对于必须分隔创建和计划的情况,可以使用构造函数,然后调用 Task.Start用于计划任务稍后执行的方法。For performance reasons, the Task.Run or TaskFactory.StartNew method is the preferred mechanism for creating and scheduling computational tasks, but for scenarios where creation and scheduling must be separated, you can use the constructors and then call the Task.Start method to schedule the task for execution at a later time.

正在等待一个或多个任务完成Waiting for one or more tasks to complete

因为任务通常在线程池线程上以异步方式运行,所以,创建和启动任务的线程会在实例化任务后立即继续执行。Because tasks typically run asynchronously on a thread pool thread, the thread that creates and starts the task continues execution as soon as the task has been instantiated. 在某些情况下,当调用线程是主应用程序线程时,应用程序可能会在任何任务实际开始执行之前终止。In some cases, when the calling thread is the main application thread, the app may terminate before any the task actually begins execution. 在其他情况下,应用程序的逻辑可能要求调用线程在一个或多个任务完成执行时继续执行。In others, your application's logic may require that the calling thread continue execution only when one or more tasks has completed execution. 可以通过调用 Wait 方法来等待一个或多个任务完成,从而同步调用线程的执行以及它启动的异步任务。You can synchronize the execution of the calling thread and the asynchronous tasks it launches by calling a Wait method to wait for one or more tasks to complete.

若要等待单个任务完成,可以调用其 Task.Wait 方法。To wait for a single task to complete, you can call its Task.Wait method. 调用 Wait 方法会阻止调用线程,直到单类实例执行完毕。A call to the Wait method blocks the calling thread until the single class instance has completed execution.

下面的示例调用无参数 Wait() 方法无条件等待,直到任务完成。The following example calls the parameterless Wait() method to wait unconditionally until a task completes. 该任务通过调用 Thread.Sleep 方法以休眠两秒钟来模拟工作。The task simulates work by calling the Thread.Sleep method to sleep for two seconds.

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

class Program
{
    static Random rand = new Random();

    static void Main()
    {
        // Wait on a single task with no timeout specified.
        Task taskA = Task.Run( () => Thread.Sleep(2000));
        Console.WriteLine("taskA Status: {0}", taskA.Status);
        try {
          taskA.Wait();
          Console.WriteLine("taskA Status: {0}", taskA.Status);
       } 
       catch (AggregateException) {
          Console.WriteLine("Exception in taskA.");
       }   
    }    
}
// The example displays output like the following:
//     taskA Status: WaitingToRun
//     taskA Status: RanToCompletion
Imports System.Threading
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      ' Wait on a single task with no timeout specified.
      Dim taskA = Task.Run( Sub() Thread.Sleep(2000))
      Console.WriteLine("taskA Status: {0}", taskA.Status)
      Try
        taskA.Wait()
        Console.WriteLine("taskA Status: {0}", taskA.Status)
      Catch e As AggregateException
         Console.WriteLine("Exception in taskA.")
      End Try
   End Sub
End Module
' The example displays output like the following:
'     taskA Status: WaitingToRun
'     taskA Status: RanToCompletion

还可以有条件地等待任务完成。You can also conditionally wait for a task to complete. Wait(Int32)Wait(TimeSpan) 方法会阻止调用线程,直到任务完成或超时间隔结束(以先达到者为准)。The Wait(Int32) and Wait(TimeSpan) methods block the calling thread until the task finishes or a timeout interval elapses, whichever comes first. 由于下面的示例将启动一个睡眠时间为两秒的任务,但定义了一秒的超时值,因此调用线程将会阻塞,直到超时过期以及任务已完成执行。Since the following example launches a task that sleeps for two seconds but defines a one-second timeout value, the calling thread blocks until the timeout expires and before the task has completed execution.

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

public class Example
{
   public static void Main()
   {
      // Wait on a single task with a timeout specified.
      Task taskA = Task.Run( () => Thread.Sleep(2000));
      try {
        taskA.Wait(1000);       // Wait for 1 second.
        bool completed = taskA.IsCompleted;
        Console.WriteLine("Task A completed: {0}, Status: {1}",
                         completed, taskA.Status);
        if (! completed)
           Console.WriteLine("Timed out before task A completed.");                 
       }
       catch (AggregateException) {
          Console.WriteLine("Exception in taskA.");
       }   
   }
}
// The example displays output like the following:
//     Task A completed: False, Status: Running
//     Timed out before task A completed.
Imports System.Threading
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      ' Wait on a single task with a timeout specified.
      Dim taskA As Task = Task.Run( Sub() Thread.Sleep(2000))
      Try
         taskA.Wait(1000)        ' Wait for 1 second.
         Dim completed As Boolean = taskA.IsCompleted
         Console.WriteLine("Task.Completed: {0}, Status: {1}",
                           completed, taskA.Status)
         If Not completed Then 
            Console.WriteLine("Timed out before task A completed.")
         End If                     
      Catch e As AggregateException
         Console.WriteLine("Exception in taskA.")
      End Try
   End Sub
End Module
' The example displays the following output:
'     Task A completed: False, Status: Running
'     Timed out before task A completed.

还可以通过调用 Wait(CancellationToken)Wait(Int32, CancellationToken) 方法来提供取消标记。You can also supply a cancellation token by calling the Wait(CancellationToken) and Wait(Int32, CancellationToken) methods. 如果在执行 Wait 方法时令牌的 IsCancellationRequested 属性 true 或变为 true,则该方法将引发 OperationCanceledExceptionIf the token's IsCancellationRequested property is true or becomes true while the Wait method is executing, the method throws an OperationCanceledException.

在某些情况下,可能需要等待一系列正在执行的任务的第一项完成,但不要在意任务是哪个。In some cases, you may want to wait for the first of a series of executing tasks to complete, but don't care which task it is. 为此,可以调用 Task.WaitAny 方法的重载之一。For this purpose, you can call one of the overloads of the Task.WaitAny method. 下面的示例创建三个任务,每个任务休眠一段时间间隔,由随机数生成器决定。The following example creates three tasks, each of which sleeps for an interval determine by a random number generator. WaitAny(Task[]) 方法等待第一个任务完成。The WaitAny(Task[]) method waits for the first task to complete. 然后,该示例显示所有三个任务的状态信息。The example then displays information about the status of all three tasks.

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

public class Example
{
   public static void Main()
   {
      var tasks = new Task[3];
      var rnd = new Random();
      for (int ctr = 0; ctr <= 2; ctr++)
         tasks[ctr] = Task.Run( () => Thread.Sleep(rnd.Next(500, 3000)));

      try {
         int index = Task.WaitAny(tasks);
         Console.WriteLine("Task #{0} completed first.\n", tasks[index].Id);
         Console.WriteLine("Status of all tasks:");
         foreach (var t in tasks)
            Console.WriteLine("   Task #{0}: {1}", t.Id, t.Status);
      }
      catch (AggregateException) {
         Console.WriteLine("An exception occurred.");
      }
   }
}
// The example displays output like the following:
//     Task #1 completed first.
//     
//     Status of all tasks:
//        Task #3: Running
//        Task #1: RanToCompletion
//        Task #4: Running
Imports System.Threading
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Dim tasks(2) As Task
      Dim rnd As New Random()
      For ctr As Integer = 0 To 2
         tasks(ctr) = Task.Run( Sub()  Thread.Sleep(rnd.Next(500, 3000)))
      Next
      
      Try 
         Dim index As Integer= Task.WaitAny(tasks)
         Console.WriteLine("Task #{0} completed first.", tasks(index).Id)
         Console.WriteLine()
         Console.WriteLine("Status of all tasks:")
         For Each t in tasks
            Console.WriteLine("   Task #{0}: {1}", t.Id, t.Status)
         Next   
      Catch e As AggregateException
         Console.WriteLine("An exception occurred.")
      End Try
   End Sub
End Module
' The example displays output like the following:
'     Task #1 completed first.
'     
'     Status of all tasks:
'        Task #3: Running
'        Task #1: RanToCompletion
'        Task #4: Running

还可以通过调用 WaitAll 方法来等待一系列任务完成。You can also wait for all of a series of tasks to complete by calling the WaitAll method. 下面的示例创建了十个任务,等待所有十个任务完成,然后显示其状态。The following example creates ten tasks, waits for all ten to complete, and then displays their status.

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

public class Example
{
   public static void Main()
   {
      // Wait for all tasks to complete.
      Task[] tasks = new Task[10];
      for (int i = 0; i < 10; i++)
      {
          tasks[i] = Task.Run(() => Thread.Sleep(2000));
      }
      try {
         Task.WaitAll(tasks);
      }
      catch (AggregateException ae) {
         Console.WriteLine("One or more exceptions occurred: ");
         foreach (var ex in ae.Flatten().InnerExceptions)
            Console.WriteLine("   {0}", ex.Message);
      }   

      Console.WriteLine("Status of completed tasks:");
      foreach (var t in tasks)
         Console.WriteLine("   Task #{0}: {1}", t.Id, t.Status);
   }
}
// The example displays the following output:
//     Status of completed tasks:
//        Task #2: RanToCompletion
//        Task #1: RanToCompletion
//        Task #3: RanToCompletion
//        Task #4: RanToCompletion
//        Task #6: RanToCompletion
//        Task #5: RanToCompletion
//        Task #7: RanToCompletion
//        Task #8: RanToCompletion
//        Task #9: RanToCompletion
//        Task #10: RanToCompletion
Imports System.Threading
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      ' Wait for all tasks to complete.
      Dim tasks(9) As Task
      For i As Integer = 0 To 9
          tasks(i) = Task.Run( Sub() Thread.Sleep(2000) )
      Next
      Try 
         Task.WaitAll(tasks)
      Catch ae As AggregateException
         Console.WriteLine("One or more exceptions occurred: ")
         For Each ex In ae.Flatten().InnerExceptions
            Console.WriteLine("   {0}", ex.Message)
         Next
      End Try   

      Console.WriteLine("Status of completed tasks:")
      For Each t in tasks
         Console.WriteLine("   Task #{0}: {1}", t.Id, t.Status)
      Next   
   End Sub
End Module
' The example displays the following output:
'     Status of completed tasks:
'        Task #2: RanToCompletion
'        Task #1: RanToCompletion
'        Task #3: RanToCompletion
'        Task #4: RanToCompletion
'        Task #6: RanToCompletion
'        Task #5: RanToCompletion
'        Task #7: RanToCompletion
'        Task #8: RanToCompletion
'        Task #9: RanToCompletion
'        Task #10: RanToCompletion

请注意,当你等待一个或多个任务完成时,正在运行的任务中引发的任何异常都将传播到调用 Wait 方法的线程上,如下面的示例所示。Note that when you wait for one or more tasks to complete, any exceptions thrown in the running tasks are propagated on the thread that calls the Wait method, as the following example shows. 它启动12个任务,其中三个任务都正常完成,三个任务引发异常。It launches 12 tasks, three of which complete normally and three of which throw an exception. 其余六个任务在开始之前会被取消,三个任务在执行时取消。Of the remaining six tasks, three are cancelled before they start, and three are cancelled while they are executing. 异常在 WaitAll 方法调用中引发,并由 try/catch 块处理。Exceptions are thrown in the WaitAll method call and are handled by a try/catch block.

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

public class Example
{
   public static void Main()
   {
      // Create a cancellation token and cancel it.
      var source1 = new CancellationTokenSource();
      var token1 = source1.Token;
      source1.Cancel();
      // Create a cancellation token for later cancellation.
      var source2 = new CancellationTokenSource();
      var token2 = source2.Token;
       
      // Create a series of tasks that will complete, be cancelled, 
      // timeout, or throw an exception.
      Task[] tasks = new Task[12];
      for (int i = 0; i < 12; i++)
      {
          switch (i % 4) 
          {
             // Task should run to completion.
             case 0:
                tasks[i] = Task.Run(() => Thread.Sleep(2000));
                break;
             // Task should be set to canceled state.
             case 1:   
                tasks[i] = Task.Run( () => Thread.Sleep(2000),
                         token1);
                break;         
             case 2:
                // Task should throw an exception.
                tasks[i] = Task.Run( () => { throw new NotSupportedException(); } );
                break;
             case 3:
                // Task should examine cancellation token.
                tasks[i] = Task.Run( () => { Thread.Sleep(2000); 
                                             if (token2.IsCancellationRequested)
                                                token2.ThrowIfCancellationRequested();
                                             Thread.Sleep(500); }, token2);   
                break;
          }
      }
      Thread.Sleep(250);
      source2.Cancel();
       
      try {
         Task.WaitAll(tasks);
      }
      catch (AggregateException ae) {
          Console.WriteLine("One or more exceptions occurred:");
          foreach (var ex in ae.InnerExceptions)
             Console.WriteLine("   {0}: {1}", ex.GetType().Name, ex.Message);
       }   

      Console.WriteLine("\nStatus of tasks:");
      foreach (var t in tasks) {
         Console.WriteLine("   Task #{0}: {1}", t.Id, t.Status);
         if (t.Exception != null) {
            foreach (var ex in t.Exception.InnerExceptions)
               Console.WriteLine("      {0}: {1}", ex.GetType().Name,
                                 ex.Message);
         }
      }
   }
}
// The example displays output like the following:
//   One or more exceptions occurred:
//      TaskCanceledException: A task was canceled.
//      NotSupportedException: Specified method is not supported.
//      TaskCanceledException: A task was canceled.
//      TaskCanceledException: A task was canceled.
//      NotSupportedException: Specified method is not supported.
//      TaskCanceledException: A task was canceled.
//      TaskCanceledException: A task was canceled.
//      NotSupportedException: Specified method is not supported.
//      TaskCanceledException: A task was canceled.
//   
//   Status of tasks:
//      Task #13: RanToCompletion
//      Task #1: Canceled
//      Task #3: Faulted
//         NotSupportedException: Specified method is not supported.
//      Task #8: Canceled
//      Task #14: RanToCompletion
//      Task #4: Canceled
//      Task #6: Faulted
//         NotSupportedException: Specified method is not supported.
//      Task #7: Canceled
//      Task #15: RanToCompletion
//      Task #9: Canceled
//      Task #11: Faulted
//         NotSupportedException: Specified method is not supported.
//      Task #12: Canceled
Imports System.Threading
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      ' Create a cancellation token and cancel it.
      Dim source1 As New CancellationTokenSource()
      Dim token1 As CancellationToken = source1.Token
      source1.Cancel()
      ' Create a cancellation token for later cancellation.
      Dim source2 As New CancellationTokenSource()
      Dim token2 As CancellationToken = source2.Token
       
      ' Create a series of tasks that will complete, be cancelled, 
      ' timeout, or throw an exception.
      Dim tasks(11) As Task
      For i As Integer = 0 To 11
          Select Case i Mod 4 
             ' Task should run to completion.
             Case 0
                tasks(i) = Task.Run( Sub() Thread.Sleep(2000))
             ' Task should be set to canceled state.
             Case 1   
                tasks(i) = Task.Run( Sub() Thread.Sleep(2000), token1)
             Case 2
                ' Task should throw an exception.
                tasks(i) = Task.Run( Sub() 
                                        Throw New NotSupportedException() 
                                     End Sub)
             Case 3
                ' Task should examine cancellation token.
                tasks(i) = Task.Run( Sub() 
                                        Thread.Sleep(2000) 
                                        If token2.IsCancellationRequested
                                           token2.ThrowIfCancellationRequested()
                                        End If
                                        Thread.Sleep(500) 
                                     End Sub, token2)   
          End Select
      Next
      Thread.Sleep(250)
      source2.Cancel()
       
      Try 
         Task.WaitAll(tasks)
      Catch ae As AggregateException
         Console.WriteLine("One or more exceptions occurred:")
         For Each ex in ae.InnerExceptions
             Console.WriteLine("   {0}: {1}", ex.GetType().Name, ex.Message)
         Next
      End Try   
      Console.WriteLine()
      
      Console.WriteLine("Status of tasks:")
      For Each t in tasks
         Console.WriteLine("   Task #{0}: {1}", t.Id, t.Status)
         If t.Exception IsNot Nothing Then
            For Each ex in t.Exception.InnerExceptions
               Console.WriteLine("      {0}: {1}", ex.GetType().Name,
                                 ex.Message)
            Next
         End If
      Next
   End Sub
End Module
' The example displays output like the following:
'   One or more exceptions occurred:
'      TaskCanceledException: A task was canceled.
'      NotSupportedException: Specified method is not supported.
'      TaskCanceledException: A task was canceled.
'      TaskCanceledException: A task was canceled.
'      NotSupportedException: Specified method is not supported.
'      TaskCanceledException: A task was canceled.
'      TaskCanceledException: A task was canceled.
'      NotSupportedException: Specified method is not supported.
'      TaskCanceledException: A task was canceled.
'   
'   Status of tasks:
'      Task #13: RanToCompletion
'      Task #1: Canceled
'      Task #3: Faulted
'         NotSupportedException: Specified method is not supported.
'      Task #8: Canceled
'      Task #14: RanToCompletion
'      Task #4: Canceled
'      Task #6: Faulted
'         NotSupportedException: Specified method is not supported.
'      Task #7: Canceled
'      Task #15: RanToCompletion
'      Task #9: Canceled
'      Task #11: Faulted
'         NotSupportedException: Specified method is not supported.
'      Task #12: Canceled

有关基于任务的异步操作中的异常处理的详细信息,请参阅异常处理For more information on exception handling in task-based asynchronous operations, see Exception Handling.

任务和区域性Tasks and culture

从面向 .NET Framework 4.6.NET Framework 4.6的桌面应用开始,创建和调用任务的线程的区域性将成为线程上下文的一部分。Starting with desktop apps that target the .NET Framework 4.6.NET Framework 4.6, the culture of the thread that creates and invokes a task becomes part of the thread's context. 也就是说,无论执行任务的线程的当前区域性如何,任务的当前区域性都是调用线程的区域性。That is, regardless of the current culture of the thread on which the task executes, the current culture of the task is the culture of the calling thread. 对于在 .NET Framework 4.6.NET Framework 4.6之前面向 .NET Framework 版本的应用,任务的区域性是执行任务的线程的区域性。For apps that target versions of the .NET Framework prior to the .NET Framework 4.6.NET Framework 4.6, the culture of the task is the culture of the thread on which the task executes. 有关详细信息,请参阅 CultureInfo 主题中的 "区域性和基于任务的异步操作" 一节。For more information, see the "Culture and task-based asynchronous operations" section in the CultureInfo topic.

备注

应用商店应用按照设置和获取默认区域性的 Windows 运行时。Store apps follow the Windows Runtime in setting and getting the default culture.

对于调试器开发人员For debugger developers

对于实现自定义调试器的开发人员而言,任务的多个内部和私有成员可能会很有用(它们可能会因发布而变化)。For developers implementing custom debuggers, several internal and private members of task may be useful (these may change from release to release). m_taskId 字段可用作 Id 属性的后备存储,但是从调试器直接访问此字段比通过属性的 getter 方法访问相同的值更有效(s_taskIdCounter 计数器用于检索任务的下一个可用 ID)。The m_taskId field serves as the backing store for the Id property, however accessing this field directly from a debugger may be more efficient than accessing the same value through the property's getter method (the s_taskIdCounter counter is used to retrieve the next available ID for a task). 同样,"m_stateFlags" 字段存储有关任务当前生命周期阶段的信息,也可以通过 Status 属性访问信息。Similarly, the m_stateFlags field stores information about the current lifecycle stage of the task, information also accessible through the Status property. "m_action" 字段存储对任务的委托的引用,而 "m_stateObject" 字段存储开发人员传递给任务的异步状态。The m_action field stores a reference to the task's delegate, and the m_stateObject field stores the async state passed to the task by the developer. 最后,对于分析堆栈帧的调试器,InternalWait 方法为任务进入等待操作的时间提供可能的标记。Finally, for debuggers that parse stack frames, the InternalWait method serves a potential marker for when a task is entering a wait operation.

构造函数

Task(Action)

使用指定的操作初始化新的 TaskInitializes a new Task with the specified action.

Task(Action, CancellationToken)

使用指定的操作和 Task 初始化新的 CancellationTokenInitializes a new Task with the specified action and CancellationToken.

Task(Action, CancellationToken, TaskCreationOptions)

使用指定的操作和创建选项初始化新的 TaskInitializes a new Task with the specified action and creation options.

Task(Action, TaskCreationOptions)

使用指定的操作和创建选项初始化新的 TaskInitializes a new Task with the specified action and creation options.

Task(Action<Object>, Object)

使用指定的操作和状态初始化新的 TaskInitializes a new Task with the specified action and state.

Task(Action<Object>, Object, CancellationToken)

使用指定的操作、状态和选项初始化新的 TaskInitializes a new Task with the specified action, state, and options.

Task(Action<Object>, Object, CancellationToken, TaskCreationOptions)

使用指定的操作、状态和选项初始化新的 TaskInitializes a new Task with the specified action, state, and options.

Task(Action<Object>, Object, TaskCreationOptions)

使用指定的操作、状态和选项初始化新的 TaskInitializes a new Task with the specified action, state, and options.

属性

AsyncState

获取在创建 Task 时提供的状态对象,如果未提供,则为 null。Gets the state object supplied when the Task was created, or null if none was supplied.

CompletedTask

获取一个已成功完成的任务。Gets a task that has already completed successfully.

CreationOptions

获取用于创建此任务的 TaskCreationOptionsGets the TaskCreationOptions used to create this task.

CurrentId

返回当前正在执行 Task 的 ID。Returns the ID of the currently executing Task.

Exception

获取导致 AggregateException 提前结束的 TaskGets the AggregateException that caused the Task to end prematurely. 如果 Task 成功完成或尚未引发任何异常,这将返回 nullIf the Task completed successfully or has not yet thrown any exceptions, this will return null.

Factory

提供对用于创建和配置 TaskTask<TResult> 实例的工厂方法的访问。Provides access to factory methods for creating and configuring Task and Task<TResult> instances.

Id

获取此 Task 实例的 ID。Gets an ID for this Task instance.

IsCanceled

获取此 Task 实例是否由于被取消的原因而已完成执行。Gets whether this Task instance has completed execution due to being canceled.

IsCompleted

获取一个值,它表示是否已完成任务。Gets a value that indicates whether the task has completed.

IsCompletedSuccessfully

了解任务是否运行到完成。Gets whether the task ran to completion.

IsFaulted

获取 Task 是否由于未经处理异常的原因而完成。Gets whether the Task completed due to an unhandled exception.

Status

获取此任务的 TaskStatusGets the TaskStatus of this task.

方法

ConfigureAwait(Boolean)

配置用于等待此 Task的 awaiter。Configures an awaiter used to await this Task.

ContinueWith(Action<Task,Object>, Object)

创建一个在目标 Task 完成时接收调用方提供的状态信息并执行的延续任务。Creates a continuation that receives caller-supplied state information and executes when the target Task completes.

ContinueWith(Action<Task,Object>, Object, CancellationToken)

创建一个在目标 Task 完成时接收调用方提供的状态信息和取消标记,并以异步方式执行的延续任务。Creates a continuation that receives caller-supplied state information and a cancellation token and that executes asynchronously when the target Task completes.

ContinueWith(Action<Task,Object>, Object, CancellationToken, TaskContinuationOptions, TaskScheduler)

创建一个在目标 Task 完成时接收调用方提供的状态信息和取消标记并执行的延续任务。Creates a continuation that receives caller-supplied state information and a cancellation token and that executes when the target Task completes. 延续任务根据一组指定的条件执行,并使用指定的计划程序。The continuation executes based on a set of specified conditions and uses a specified scheduler.

ContinueWith(Action<Task,Object>, Object, TaskContinuationOptions)

创建一个在目标 Task 完成时接收调用方提供的状态信息并执行的延续任务。Creates a continuation that receives caller-supplied state information and executes when the target Task completes. 延续任务根据一组指定的条件执行。The continuation executes based on a set of specified conditions.

ContinueWith(Action<Task,Object>, Object, TaskScheduler)

创建一个在目标 Task 完成时接收调用方提供的状态信息并以异步方式执行的延续任务。Creates a continuation that receives caller-supplied state information and executes asynchronously when the target Task completes. 延续任务使用指定计划程序。The continuation uses a specified scheduler.

ContinueWith(Action<Task>)

创建一个在目标 Task 完成时异步执行的延续任务。Creates a continuation that executes asynchronously when the target Task completes.

ContinueWith(Action<Task>, CancellationToken)

创建一个在目标 Task 完成时可接收取消标记并以异步方式执行的延续任务。Creates a continuation that receives a cancellation token and executes asynchronously when the target Task completes.

ContinueWith(Action<Task>, CancellationToken, TaskContinuationOptions, TaskScheduler)

创建一个在目标任务完成时按照指定的 TaskContinuationOptions 执行的延续任务。Creates a continuation that executes when the target task competes according to the specified TaskContinuationOptions. 延续任务会收到一个取消标记,并使用指定的计划程序。The continuation receives a cancellation token and uses a specified scheduler.

ContinueWith(Action<Task>, TaskContinuationOptions)

创建一个在目标任务完成时按照指定的 TaskContinuationOptions 执行的延续任务。Creates a continuation that executes when the target task completes according to the specified TaskContinuationOptions.

ContinueWith(Action<Task>, TaskScheduler)

创建一个在目标 Task 完成时异步执行的延续任务。Creates a continuation that executes asynchronously when the target Task completes. 延续任务使用指定计划程序。The continuation uses a specified scheduler.

ContinueWith<TResult>(Func<Task,Object,TResult>, Object)

创建一个在目标 Task 完成并返回一个值时接收调用方提供的状态信息并以异步方式执行的延续任务。Creates a continuation that receives caller-supplied state information and executes asynchronously when the target Task completes and returns a value.

ContinueWith<TResult>(Func<Task,Object,TResult>, Object, CancellationToken)

创建一个在目标 Task 完成时异步执行并返回一个值的延续任务。Creates a continuation that executes asynchronously when the target Task completes and returns a value. 延续任务接收调用方提供的状态信息和取消标记。The continuation receives caller-supplied state information and a cancellation token.

ContinueWith<TResult>(Func<Task,Object,TResult>, Object, CancellationToken, TaskContinuationOptions, TaskScheduler)

创建一个在目标 Task 完成并返回一个值时根据指定的任务延续选项执行的延续任务。Creates a continuation that executes based on the specified task continuation options when the target Task completes and returns a value. 延续任务接收调用方提供的状态信息和取消标记,并使用指定的计划程序。The continuation receives caller-supplied state information and a cancellation token and uses the specified scheduler.

ContinueWith<TResult>(Func<Task,Object,TResult>, Object, TaskContinuationOptions)

创建一个在目标 Task 完成时根据指定的任务延续选项执行的延续任务。Creates a continuation that executes based on the specified task continuation options when the target Task completes. 延续任务接收调用方提供的状态信息。The continuation receives caller-supplied state information.

ContinueWith<TResult>(Func<Task,Object,TResult>, Object, TaskScheduler)

创建一个在目标 Task 完成时异步执行的延续任务。Creates a continuation that executes asynchronously when the target Task completes. 延续任务接收调用方提供的状态信息,并使用指定的计划程序。The continuation receives caller-supplied state information and uses a specified scheduler.

ContinueWith<TResult>(Func<Task,TResult>)

创建一个在目标 Task<TResult> 完成时异步执行并返回一个值的延续任务。Creates a continuation that executes asynchronously when the target Task<TResult> completes and returns a value.

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

创建一个在目标 Task 完成时异步执行并返回一个值的延续任务。Creates a continuation that executes asynchronously when the target Task completes and returns a value. 延续任务收到取消标记。The continuation receives a cancellation token.

ContinueWith<TResult>(Func<Task,TResult>, CancellationToken, TaskContinuationOptions, TaskScheduler)

创建一个按照指定延续任务选项执行并返回一个值的延续任务。Creates a continuation that executes according to the specified continuation options and returns a value. 延续任务被传入一个取消标记,并使用指定的计划程序。The continuation is passed a cancellation token and uses a specified scheduler.

ContinueWith<TResult>(Func<Task,TResult>, TaskContinuationOptions)

创建一个按照指定延续任务选项执行并返回一个值的延续任务。Creates a continuation that executes according to the specified continuation options and returns a value.

ContinueWith<TResult>(Func<Task,TResult>, TaskScheduler)

创建一个在目标 Task 完成时异步执行并返回一个值的延续任务。Creates a continuation that executes asynchronously when the target Task completes and returns a value. 延续任务使用指定计划程序。The continuation uses a specified scheduler.

Delay(Int32)

创建一个在指定的毫秒数后完成的任务。Creates a task that completes after a specified number of milliseconds.

Delay(Int32, CancellationToken)

创建一个在指定的毫秒数后完成的可取消任务。Creates a cancellable task that completes after a specified number of milliseconds.

Delay(TimeSpan)

创建一个在指定的时间间隔后完成的任务。Creates a task that completes after a specified time interval.

Delay(TimeSpan, CancellationToken)

创建一个在指定的时间间隔后完成的可取消任务。Creates a cancellable task that completes after a specified time interval.

Dispose()

释放 Task 类的当前实例所使用的所有资源。Releases all resources used by the current instance of the Task class.

Dispose(Boolean)

释放 Task,同时释放其所有非托管资源。Disposes the Task, releasing all of its unmanaged resources.

Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(继承自 Object)
FromCanceled(CancellationToken)

创建 Task,它因指定的取消标记进行的取消操作而完成。Creates a Task that's completed due to cancellation with a specified cancellation token.

FromCanceled<TResult>(CancellationToken)

创建 Task<TResult>,它因指定的取消标记进行的取消操作而完成。Creates a Task<TResult> that's completed due to cancellation with a specified cancellation token.

FromException(Exception)

创建 Task,它在完成后出现指定的异常。Creates a Task that has completed with a specified exception.

FromException<TResult>(Exception)

创建 Task<TResult>,它在完成后出现指定的异常。Creates a Task<TResult> that's completed with a specified exception.

FromResult<TResult>(TResult)

创建指定结果的、成功完成的 Task<TResult>Creates a Task<TResult> that's completed successfully with the specified result.

GetAwaiter()

获取用于等待此 Task 的 awaiter。Gets an awaiter used to await this Task.

GetHashCode()

用作默认哈希函数。Serves as the default hash function.

(继承自 Object)
GetType()

获取当前实例的 TypeGets the Type of the current instance.

(继承自 Object)
MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)
Run(Action)

将在线程池上运行的指定工作排队,并返回代表该工作的 Task 对象。Queues the specified work to run on the thread pool and returns a Task object that represents that work.

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

将在线程池上运行的指定工作排队,并返回 function 所返回的任务的代理项。Queues the specified work to run on the thread pool and returns a proxy for the task returned by function.

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

将在线程池上运行的指定工作排队,并返回代表该工作的 Task<TResult> 对象。Queues the specified work to run on the thread pool and returns a Task<TResult> object that represents that work.

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.

RunSynchronously()

对当前的 Task 同步运行 TaskSchedulerRuns the Task synchronously on the current TaskScheduler.

RunSynchronously(TaskScheduler)

对提供的 Task 同步运行 TaskSchedulerRuns the Task synchronously on the TaskScheduler provided.

Start()

启动 Task,并将它安排到当前的 TaskScheduler 中执行。Starts the Task, scheduling it for execution to the current TaskScheduler.

Start(TaskScheduler)

启动 Task,并将它安排到指定的 TaskScheduler 中执行。Starts the Task, scheduling it for execution to the specified TaskScheduler.

ToString()

返回一个表示当前对象的 string。Returns a string that represents the current object.

(继承自 Object)
Wait()

等待 Task 完成执行过程。Waits for the Task to complete execution.

Wait(CancellationToken)

等待 Task 完成执行过程。Waits for the Task to complete execution. 如果在任务完成之前取消标记已取消,等待将终止。The wait terminates if a cancellation token is canceled before the task completes.

Wait(Int32)

等待 Task 在指定的毫秒数内完成执行。Waits for the Task to complete execution within a specified number of milliseconds.

Wait(Int32, CancellationToken)

等待 Task 完成执行过程。Waits for the Task to complete execution. 如果在任务完成之前超时间隔结束或取消标记已取消,等待将终止。The wait terminates if a timeout interval elapses or a cancellation token is canceled before the task completes.

Wait(TimeSpan)

等待 Task 在指定的时间间隔内完成执行。Waits for the Task to complete execution within a specified time interval.

WaitAll(Task[])

等待提供的所有 Task 对象完成执行过程。Waits for all of the provided Task objects to complete execution.

WaitAll(Task[], CancellationToken)

等待提供的所有 Task 对象完成执行过程(除非取消等待)。Waits for all of the provided Task objects to complete execution unless the wait is cancelled.

WaitAll(Task[], Int32)

等待所有提供的 Task 在指定的毫秒数内完成执行。Waits for all of the provided Task objects to complete execution within a specified number of milliseconds.

WaitAll(Task[], Int32, CancellationToken)

等待提供的所有 Task 对象在指定的毫秒数内完成执行,或等到取消等待。Waits for all of the provided Task objects to complete execution within a specified number of milliseconds or until the wait is cancelled.

WaitAll(Task[], TimeSpan)

等待所有提供的可取消 Task 对象在指定的时间间隔内完成执行。Waits for all of the provided cancellable Task objects to complete execution within a specified time interval.

WaitAny(Task[])

等待提供的任一 Task 对象完成执行过程。Waits for any of the provided Task objects to complete execution.

WaitAny(Task[], CancellationToken)

等待提供的任何 Task 对象完成执行过程(除非取消等待)。Waits for any of the provided Task objects to complete execution unless the wait is cancelled.

WaitAny(Task[], Int32)

等待任何提供的 Task 对象在指定的毫秒数内完成执行。Waits for any of the provided Task objects to complete execution within a specified number of milliseconds.

WaitAny(Task[], Int32, CancellationToken)

等待提供的任何 Task 对象在指定的毫秒数内完成执行,或等到取消标记取消。Waits for any of the provided Task objects to complete execution within a specified number of milliseconds or until a cancellation token is cancelled.

WaitAny(Task[], TimeSpan)

等待任何提供的 Task 对象在指定的时间间隔内完成执行。Waits for any of the provided Task objects to complete execution within a specified time interval.

WhenAll(IEnumerable<Task>)

创建一个任务,该任务将在可枚举集合中的所有 Task 对象都已完成时完成。Creates a task that will complete when all of the Task objects in an enumerable collection have completed.

WhenAll(Task[])

创建一个任务,该任务将在数组中的所有 Task 对象都已完成时完成。Creates a task that will complete when all of the Task objects in an array have completed.

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

创建一个任务,该任务将在可枚举集合中的所有 Task<TResult> 对象都已完成时完成。Creates a task that will complete when all of the Task<TResult> objects in an enumerable collection have completed.

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

创建一个任务,该任务将在数组中的所有 Task<TResult> 对象都已完成时完成。Creates a task that will complete when all of the Task<TResult> objects in an array have completed.

WhenAny(IEnumerable<Task>)

任何提供的任务已完成时,创建将完成的任务。Creates a task that will complete when any of the supplied tasks have completed.

WhenAny(Task[])

任何提供的任务已完成时,创建将完成的任务。Creates a task that will complete when any of the supplied tasks have completed.

WhenAny<TResult>(IEnumerable<Task<TResult>>)

任何提供的任务已完成时,创建将完成的任务。Creates a task that will complete when any of the supplied tasks have completed.

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

任何提供的任务已完成时,创建将完成的任务。Creates a task that will complete when any of the supplied tasks have completed.

Yield()

创建异步产生当前上下文的等待任务。Creates an awaitable task that asynchronously yields back to the current context when awaited.

显式界面实现

IAsyncResult.AsyncWaitHandle

获取可用于等待任务完成的 WaitHandleGets a WaitHandle that can be used to wait for the task to complete.

IAsyncResult.CompletedSynchronously

获取操作是否已同步完成的指示。Gets an indication of whether the operation completed synchronously.

扩展方法

DispatcherOperationWait(Task)

无限期等待完成基础 DispatcherOperationWaits indefinitely for the underlying DispatcherOperation to complete.

DispatcherOperationWait(Task, TimeSpan)

等待基础 DispatcherOperation 完成,直到达到指定的所需时间。Waits for the specified amount of time for the underlying DispatcherOperation to complete.

IsDispatcherOperationTask(Task)

返回一个值,该值指示此 Task 是否与 DispatcherOperation 相关。Returns a value that indicates whether this Task is associated with a DispatcherOperation.

AsAsyncAction(Task)

返回表示已开始任务的 Windows 运行时异步操作。Returns a Windows Runtime asynchronous action that represents a started task.

适用于

线程安全性

Dispose()以外,Task的所有成员都是线程安全的,可同时从多个线程使用。All members of Task, except for Dispose(), are thread-safe and may be used from multiple threads concurrently.

另请参阅