Task Task Task Task Class

定义

表示一个异步操作。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
继承
TaskTaskTaskTask
派生
实现

注解

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属性,并将IsCanceledIsCompleted,和IsFaulted属性,以确定任务的状态。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. 三个任务执行Action<T>名为的委托action,这样便可以接受类型的自变量ObjectThree 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通过调用任务类构造函数,实例化但开始通过调用其Start()方法仅在任务后面t2已开始。Task t1 is instantiated by calling a Task class constructor, but is started by calling its Start() method only after task t2 has started.

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

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

  • 任务t4是以同步方式执行主线程上调用RunSynchronously()方法。Task t4 is executed synchronously on the main thread by calling the RunSynchronously() method.

因为任务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. 由于下面的示例将启动一个任务,休眠 2 秒,但定义的一秒的超时值,调用线程受到阻止,直到在超时到期之前, 已完成执行的任务。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. 如果该令牌的IsCancellationRequested属性是true或变得true虽然Wait执行方法,该方法将引发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 的应用, .NET Framework 4.6.NET Framework 4.6,任务的区域性是执行该任务时的线程的区域性。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) Task(Action) Task(Action) Task(Action)

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

Task(Action, CancellationToken) Task(Action, CancellationToken) Task(Action, CancellationToken) Task(Action, CancellationToken)

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

Task(Action, CancellationToken, TaskCreationOptions) Task(Action, CancellationToken, TaskCreationOptions) Task(Action, CancellationToken, TaskCreationOptions) Task(Action, CancellationToken, TaskCreationOptions)

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

Task(Action, TaskCreationOptions) Task(Action, TaskCreationOptions) Task(Action, TaskCreationOptions) Task(Action, TaskCreationOptions)

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

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

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

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

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

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

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

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

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

属性

AsyncState AsyncState AsyncState AsyncState

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

CompletedTask CompletedTask CompletedTask CompletedTask

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

CreationOptions CreationOptions CreationOptions CreationOptions

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

CurrentId CurrentId CurrentId CurrentId

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

Exception Exception Exception 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 Factory Factory Factory

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

Id Id Id Id

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

IsCanceled IsCanceled IsCanceled IsCanceled

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

IsCompleted IsCompleted IsCompleted IsCompleted

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

IsCompletedSuccessfully IsCompletedSuccessfully IsCompletedSuccessfully IsCompletedSuccessfully
IsFaulted IsFaulted IsFaulted IsFaulted

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

Status Status Status Status

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

方法

ConfigureAwait(Boolean) ConfigureAwait(Boolean) ConfigureAwait(Boolean) ConfigureAwait(Boolean)

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

ContinueWith(Action<Task,Object>, Object) ContinueWith(Action<Task,Object>, Object) ContinueWith(Action<Task,Object>, Object) 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) ContinueWith(Action<Task,Object>, Object, CancellationToken) ContinueWith(Action<Task,Object>, Object, CancellationToken) 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) ContinueWith(Action<Task,Object>, Object, CancellationToken, TaskContinuationOptions, TaskScheduler) ContinueWith(Action<Task,Object>, Object, CancellationToken, TaskContinuationOptions, TaskScheduler) 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) ContinueWith(Action<Task,Object>, Object, TaskContinuationOptions) ContinueWith(Action<Task,Object>, Object, TaskContinuationOptions) 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) ContinueWith(Action<Task,Object>, Object, TaskScheduler) ContinueWith(Action<Task,Object>, Object, TaskScheduler) 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>) ContinueWith(Action<Task>) ContinueWith(Action<Task>) ContinueWith(Action<Task>)

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

ContinueWith(Action<Task>, CancellationToken) ContinueWith(Action<Task>, CancellationToken) ContinueWith(Action<Task>, CancellationToken) 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) ContinueWith(Action<Task>, CancellationToken, TaskContinuationOptions, TaskScheduler) ContinueWith(Action<Task>, CancellationToken, TaskContinuationOptions, TaskScheduler) 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) ContinueWith(Action<Task>, TaskContinuationOptions) ContinueWith(Action<Task>, TaskContinuationOptions) ContinueWith(Action<Task>, TaskContinuationOptions)

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

ContinueWith(Action<Task>, TaskScheduler) ContinueWith(Action<Task>, TaskScheduler) ContinueWith(Action<Task>, TaskScheduler) 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) ContinueWith<TResult>(Func<Task,Object,TResult>, Object) ContinueWith<TResult>(Func<Task,Object,TResult>, Object) 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) ContinueWith<TResult>(Func<Task,Object,TResult>, Object, CancellationToken) ContinueWith<TResult>(Func<Task,Object,TResult>, Object, CancellationToken) 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) ContinueWith<TResult>(Func<Task,Object,TResult>, Object, CancellationToken, TaskContinuationOptions, TaskScheduler) ContinueWith<TResult>(Func<Task,Object,TResult>, Object, CancellationToken, TaskContinuationOptions, TaskScheduler) 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) ContinueWith<TResult>(Func<Task,Object,TResult>, Object, TaskContinuationOptions) ContinueWith<TResult>(Func<Task,Object,TResult>, Object, TaskContinuationOptions) 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) ContinueWith<TResult>(Func<Task,Object,TResult>, Object, TaskScheduler) ContinueWith<TResult>(Func<Task,Object,TResult>, Object, TaskScheduler) 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>) ContinueWith<TResult>(Func<Task,TResult>) ContinueWith<TResult>(Func<Task,TResult>) 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) ContinueWith<TResult>(Func<Task,TResult>, CancellationToken) ContinueWith<TResult>(Func<Task,TResult>, CancellationToken) 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) ContinueWith<TResult>(Func<Task,TResult>, CancellationToken, TaskContinuationOptions, TaskScheduler) ContinueWith<TResult>(Func<Task,TResult>, CancellationToken, TaskContinuationOptions, TaskScheduler) 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) ContinueWith<TResult>(Func<Task,TResult>, TaskContinuationOptions) ContinueWith<TResult>(Func<Task,TResult>, TaskContinuationOptions) 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) ContinueWith<TResult>(Func<Task,TResult>, TaskScheduler) ContinueWith<TResult>(Func<Task,TResult>, TaskScheduler) 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) Delay(Int32) Delay(Int32) Delay(Int32)

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

Delay(Int32, CancellationToken) Delay(Int32, CancellationToken) Delay(Int32, CancellationToken) Delay(Int32, CancellationToken)

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

Delay(TimeSpan) Delay(TimeSpan) Delay(TimeSpan) Delay(TimeSpan)

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

Delay(TimeSpan, CancellationToken) Delay(TimeSpan, CancellationToken) Delay(TimeSpan, CancellationToken) Delay(TimeSpan, CancellationToken)

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

Dispose() Dispose() Dispose() Dispose()

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

Dispose(Boolean) Dispose(Boolean) Dispose(Boolean) Dispose(Boolean)

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

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

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

(Inherited from Object)
FromCanceled(CancellationToken) FromCanceled(CancellationToken) FromCanceled(CancellationToken) FromCanceled(CancellationToken)

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

FromCanceled<TResult>(CancellationToken) FromCanceled<TResult>(CancellationToken) FromCanceled<TResult>(CancellationToken) FromCanceled<TResult>(CancellationToken)

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

FromException(Exception) FromException(Exception) FromException(Exception) FromException(Exception)

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

FromException<TResult>(Exception) FromException<TResult>(Exception) FromException<TResult>(Exception) FromException<TResult>(Exception)

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

FromResult<TResult>(TResult) FromResult<TResult>(TResult) FromResult<TResult>(TResult) FromResult<TResult>(TResult)

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

GetAwaiter() GetAwaiter() GetAwaiter() GetAwaiter()

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

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

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

(Inherited from Object)
GetType() GetType() GetType() GetType()

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

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

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

(Inherited from Object)
Run(Action) 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(Action, CancellationToken) 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>) 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(Func<Task>, CancellationToken) 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<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<Task<TResult>>, CancellationToken) 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<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<TResult>(Func<TResult>, CancellationToken) 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.

RunSynchronously() RunSynchronously() RunSynchronously() RunSynchronously()

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

RunSynchronously(TaskScheduler) RunSynchronously(TaskScheduler) RunSynchronously(TaskScheduler) RunSynchronously(TaskScheduler)

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

Start() Start() Start() Start()

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

Start(TaskScheduler) Start(TaskScheduler) Start(TaskScheduler) Start(TaskScheduler)

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

ToString() ToString() ToString() ToString()

返回表示当前对象的字符串。Returns a string that represents the current object.

(Inherited from Object)
Wait() Wait() Wait() Wait()

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

Wait(CancellationToken) Wait(CancellationToken) Wait(CancellationToken) 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) Wait(Int32) Wait(Int32) Wait(Int32)

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

Wait(Int32, CancellationToken) Wait(Int32, CancellationToken) Wait(Int32, CancellationToken) 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) Wait(TimeSpan) Wait(TimeSpan) Wait(TimeSpan)

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

WaitAll(Task[]) WaitAll(Task[]) WaitAll(Task[]) WaitAll(Task[])

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

WaitAll(Task[], CancellationToken) WaitAll(Task[], CancellationToken) WaitAll(Task[], CancellationToken) WaitAll(Task[], CancellationToken)

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

WaitAll(Task[], Int32) WaitAll(Task[], Int32) WaitAll(Task[], Int32) 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) WaitAll(Task[], Int32, CancellationToken) WaitAll(Task[], Int32, CancellationToken) 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) WaitAll(Task[], TimeSpan) WaitAll(Task[], TimeSpan) WaitAll(Task[], TimeSpan)

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

WaitAny(Task[]) WaitAny(Task[]) WaitAny(Task[]) WaitAny(Task[])

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

WaitAny(Task[], CancellationToken) WaitAny(Task[], CancellationToken) WaitAny(Task[], CancellationToken) WaitAny(Task[], CancellationToken)

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

WaitAny(Task[], Int32) WaitAny(Task[], Int32) WaitAny(Task[], Int32) 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) WaitAny(Task[], Int32, CancellationToken) WaitAny(Task[], Int32, CancellationToken) 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) WaitAny(Task[], TimeSpan) WaitAny(Task[], TimeSpan) WaitAny(Task[], TimeSpan)

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

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

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

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

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

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

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

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

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

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

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

WhenAny(Task[]) WhenAny(Task[]) WhenAny(Task[]) WhenAny(Task[])

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

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

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

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

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

Yield() Yield() Yield() Yield()

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

显式界面实现

IAsyncResult.AsyncWaitHandle IAsyncResult.AsyncWaitHandle IAsyncResult.AsyncWaitHandle IAsyncResult.AsyncWaitHandle

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

IAsyncResult.CompletedSynchronously IAsyncResult.CompletedSynchronously IAsyncResult.CompletedSynchronously IAsyncResult.CompletedSynchronously

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

扩展方法

DispatcherOperationWait(Task) DispatcherOperationWait(Task) DispatcherOperationWait(Task) DispatcherOperationWait(Task)

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

DispatcherOperationWait(Task, TimeSpan) DispatcherOperationWait(Task, TimeSpan) DispatcherOperationWait(Task, TimeSpan) DispatcherOperationWait(Task, TimeSpan)

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

IsDispatcherOperationTask(Task) IsDispatcherOperationTask(Task) IsDispatcherOperationTask(Task) IsDispatcherOperationTask(Task)

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

AsAsyncAction(Task) AsAsyncAction(Task) AsAsyncAction(Task) AsAsyncAction(Task)

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

适用于

线程安全性

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

另请参阅