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. 因為下列範例會啟動的工作,會進入睡眠狀態兩秒,但定義一秒等候逾時值,則呼叫端執行緒會封鎖直到逾時到期,以及之前工作已完成執行。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. 下列範例會建立 10 個工作、 等候所有十個完成,然後顯示其狀態。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計數器用來擷取工作的下一個可用識別碼。)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

提供 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,並釋放它的所有 Unmanaged 資源。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)

建立以指定的取消語彙基元取消而完成的 TaskCreates 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)

建立以指定例外狀況完成的 TaskCreates 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 的 awaiter。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 的淺層複本 (Shallow Copy)。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 所傳回之工作的 Proxy。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 所傳回之工作的 Proxy。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) 的 Proxy。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) 的 Proxy。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()

建立會在等候時以非同步方式遞交 (Yield) 給目前內容的 awaitable 工具。Creates an awaitable task that asynchronously yields back to the current context when awaited.

明確介面實作

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

取得 WaitHandle,這個項目可用來等候工作完成。Gets 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.

Extension Methods

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

無限期等候基礎 DispatcherOperation 完成。Waits 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.

另請參閱