Task 類別

定義

表示非同步作業。Represents an asynchronous operation.

public ref class Task : IAsyncResult, IDisposable
public class Task : IAsyncResult, IDisposable
type Task = class
    interface IAsyncResult
    interface IDisposable
Public Class Task
Implements IAsyncResult, IDisposable
繼承
Task
衍生
實作

備註

@No__t-0 類別代表不會傳回值,而且通常會以非同步方式執行的單一作業。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. 由於 @no__t 0 物件所執行的工作通常會線上程集區執行緒上以非同步方式執行,而不是在主應用程式執行緒上同步執行,因此您可以使用 Status 屬性以及 IsCanceledIsCompletedIsFaulted 屬性,以判斷工作的狀態。Because the work performed by a Task object typically executes asynchronously on a thread pool thread rather than synchronously on the main application thread, you can use the Status property, as well as the IsCanceled, IsCompleted, and IsFaulted properties, to determine the state of a task. 最常見的情況是使用 lambda 運算式來指定工作要執行的工作。Most commonly, a lambda expression is used to specify the work that the task is to perform.

針對傳回值的作業,您可以使用 Task<TResult> 類別。For operations that return values, you use the Task<TResult> class.

本節內容:In this section:

工作具現化範例 Task instantiation examples
建立和執行工作 Creating and executing a task
分隔工作建立和執行 Separating task creation and execution
正在等候一或多個工作完成 Waiting for one or more tasks to complete
工作和文化特性 Tasks and culture
偵錯工具開發人員For debugger developers

工作具現化Task instantiation

下列範例會建立並執行四項工作。The following example creates and executes four tasks. 三項工作會執行名為 action 的 @no__t 0 委派,它會接受 Object 類型的引數。Three tasks execute an Action<T> delegate named action, which accepts an argument of type Object. 第四個工作會執行 lambda 運算式(@no__t 0 委派),此作業會在工作建立方法的呼叫中以內嵌方式定義。A fourth task executes a lambda expression (an Action delegate) that is defined inline in the call to the task creation method. 每項工作都具現化,並以不同的方式執行:Each task is instantiated and run in a different way:

  • 工作 t1 是藉由呼叫工作類別的函式來具現化,但只有在工作 t2 啟動後,才會呼叫其 Start() 方法來啟動。Task t1 is instantiated by calling a Task class constructor, but is started by calling its Start() method only after task t2 has started.

  • 工作 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. @No__t-0 方法提供簡單的方法,讓您使用預設值來啟動工作,而不需要額外的參數。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. @No__t-0 屬性會傳回 TaskFactory 物件。The Task.Factory property returns a TaskFactory object. @No__t (0)方法的多載可讓您指定參數,以傳遞至工作建立選項和工作排程器。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

@No__t 0 類別也會提供將工作初始化但不會排程執行的函式。The Task class also provides constructors that initialize the task but that do not schedule it for execution. 基於效能考慮,Task.Run 或 @no__t 1 方法是建立和排程計算工作的慣用機制,但對於必須分隔建立和排程的案例,您可以使用這些函式,然後呼叫 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. @No__t-0 和 @no__t 1 方法會封鎖呼叫執行緒,直到工作完成或逾時間隔過後(以先發生者為准)。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. 如果 token 的 IsCancellationRequested 屬性為 true,或在執行 Wait 方法時變成 true,則方法會擲回 OperationCanceledExceptionIf the token's IsCancellationRequested property is true or becomes true while the Wait method is executing, the method throws an OperationCanceledException.

在某些情況下,您可能會想要等待一系列執行中工作的第一個作業完成,但不在意它是哪一項。In some cases, you may want to wait for the first of a series of executing tasks to complete, but don't care which task it is. 基於此目的,您可以呼叫 Task.WaitAny 方法的其中一個多載。For this purpose, you can call one of the overloads of the Task.WaitAny method. 下列範例會建立三個工作,每個工作都會進入睡眠狀態,而間隔會由亂數字產生器決定。The following example creates three tasks, each of which sleeps for an interval determine by a random number generator. @No__t-0 方法會等候第一個工作完成。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 @ no__t-2 @ no__t-3 區塊處理。Exceptions are thrown in the WaitAll method call and are handled by a try/catch block.

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

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

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

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

如需以工作為基礎的非同步作業中例外狀況處理的詳細資訊,請參閱例外狀況處理For more information on exception handling in task-based asynchronous operations, see Exception Handling.

工作和文化特性Tasks and culture

從以 .NET Framework 4.6.NET Framework 4.6 為目標的桌面應用程式開始,建立和叫用工作之執行緒的文化特性會成為執行緒內容的一部分。Starting with desktop apps that target the .NET Framework 4.6.NET Framework 4.6, the culture of the thread that creates and invokes a task becomes part of the thread's context. 也就是說,不論工作執行所在之執行緒的目前文化特性為何,工作的目前文化特性都是呼叫執行緒的文化特性。That is, regardless of the current culture of the thread on which the task executes, the current culture of the task is the culture of the calling thread. 對於以 .NET Framework 4.6.NET Framework 4.6 之前的 .NET Framework 版本為目標的應用程式,工作的文化特性就是工作執行所在之執行緒的文化特性。For apps that target versions of the .NET Framework prior to the .NET Framework 4.6.NET Framework 4.6, the culture of the task is the culture of the thread on which the task executes. 如需詳細資訊,請參閱 CultureInfo 主題中的「文化特性和以工作為基礎的非同步作業」一節。For more information, see the "Culture and task-based asynchronous operations" section in the CultureInfo topic.

注意

Store 應用程式遵循設定和取得預設文化特性中的 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). @No__t-0 欄位做為 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. [@No__t-0] 欄位會儲存工作委派的參考,而 [@no__t 1] 欄位會儲存由開發人員傳遞給工作的非同步狀態。The m_action field stores a reference to the task's delegate, and the m_stateObject field stores the async state passed to the task by the developer. 最後,針對剖析堆疊框架的偵錯工具,InternalWait 方法可在工作進入等候作業時,提供可能的標記。Finally, for debuggers that parse stack frames, the InternalWait method serves a potential marker for when a task is entering a wait operation.

建構函式

Task(Action)

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

Task(Action, CancellationToken)

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

Task(Action, CancellationToken, TaskCreationOptions)

使用指定的動作和建立選項,初始化新的 TaskInitializes a new Task with the specified action and creation options.

Task(Action, TaskCreationOptions)

使用指定的動作和建立選項,初始化新的 TaskInitializes a new Task with the specified action and creation options.

Task(Action<Object>, Object)

使用指定的動作和狀態,初始化新的 TaskInitializes a new Task with the specified action and state.

Task(Action<Object>, Object, CancellationToken)

使用指定的動作、狀態和選項,初始化新的 TaskInitializes a new Task with the specified action, state, and options.

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

使用指定的動作、狀態和選項,初始化新的 TaskInitializes a new Task with the specified action, state, and options.

Task(Action<Object>, Object, TaskCreationOptions)

使用指定的動作、狀態和選項,初始化新的 TaskInitializes a new Task with the specified action, state, and options.

屬性

AsyncState

取得建立 Task 時提供的狀態物件,如果未提供則為 null。Gets the state object supplied when the Task was created, or null if none was supplied.

CompletedTask

取得已成功完成的工作。Gets a task that has already completed successfully.

CreationOptions

取得用來建立這個工作的 TaskCreationOptionsGets the TaskCreationOptions used to create this task.

CurrentId

傳回目前執行之 Task 的唯一 ID。Returns the ID of the currently executing Task.

Exception

取得導致 AggregateException 不當結束的 TaskGets the AggregateException that caused the Task to end prematurely. 如果 Task 順利完成,或未擲回任何例外狀況,則這會傳回 nullIf the Task completed successfully or has not yet thrown any exceptions, this will return null.

Factory

提供 Factory 方法的存取,這些 Factory 方法用於建立及設定 TaskTask<TResult> 執行個體。Provides access to factory methods for creating and configuring Task and Task<TResult> instances.

Id

取得這個 Task 執行個體的 ID。Gets an ID for this Task instance.

IsCanceled

取得這個 Task 執行個體是否因取消才完成執行。Gets whether this Task instance has completed execution due to being canceled.

IsCompleted

取得值,這個值表示工作是否已經完成。Gets a value that indicates whether the task has completed.

IsCompletedSuccessfully

取得工作是否執行到完成。Gets whether the task ran to completion.

IsFaulted

取得 Task 是否因未處理的例外狀況才完成。Gets whether the Task completed due to an unhandled exception.

Status

取得這個工作的 TaskStatusGets the TaskStatus of this task.

方法

ConfigureAwait(Boolean)

設定用來等候這個 Task 的 awaiter。Configures an awaiter used to await this Task.

ContinueWith(Action<Task,Object>, Object)

建立當目標 Task 完成時,會接收呼叫端提供的狀態資訊並執行的接續。Creates a continuation that receives caller-supplied state information and executes when the target Task completes.

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

建立當目標 Task 完成時,會接收呼叫端提供的狀態資訊和取消語彙基元,並非同步執行的接續。Creates a continuation that receives caller-supplied state information and a cancellation token and that executes asynchronously when the target Task completes.

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

建立當目標 Task 完成時,會接收呼叫端提供的狀態資訊和取消語彙基元,並執行的接續。Creates a continuation that receives caller-supplied state information and a cancellation token and that executes when the target Task completes. 接續會根據一組指定的條件執行,並使用指定的排程器。The continuation executes based on a set of specified conditions and uses a specified scheduler.

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

建立當目標 Task 完成時,會接收呼叫端提供的狀態資訊並執行的接續。Creates a continuation that receives caller-supplied state information and executes when the target Task completes. 接續會根據一組指定的條件執行。The continuation executes based on a set of specified conditions.

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

建立當目標 Task 完成時,會接收呼叫端提供的狀態資訊並非同步執行的接續。Creates a continuation that receives caller-supplied state information and executes asynchronously when the target Task completes. 接續會使用指定的排程器。The continuation uses a specified scheduler.

ContinueWith(Action<Task>)

建立當目標 Task 完成時非同步執行的接續。Creates a continuation that executes asynchronously when the target Task completes.

ContinueWith(Action<Task>, CancellationToken)

建立當目標 Task 完成時,會接收取消語彙基元並非同步執行的接續。Creates a continuation that receives a cancellation token and executes asynchronously when the target Task completes.

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

建立當目標工作完成時,會根據指定之 TaskContinuationOptions 執行的接續。Creates a continuation that executes when the target task competes according to the specified TaskContinuationOptions. 接續會接收取消語彙基元,並使用指定的排程器。The continuation receives a cancellation token and uses a specified scheduler.

ContinueWith(Action<Task>, TaskContinuationOptions)

建立當目標工作完成時,會根據指定之 TaskContinuationOptions 執行的接續。Creates a continuation that executes when the target task completes according to the specified TaskContinuationOptions.

ContinueWith(Action<Task>, TaskScheduler)

建立當目標 Task 完成時非同步執行的接續。Creates a continuation that executes asynchronously when the target Task completes. 接續會使用指定的排程器。The continuation uses a specified scheduler.

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

建立當目標 Task 完成並傳回值時,會接收呼叫端提供的狀態資訊並非同步執行的接續。Creates a continuation that receives caller-supplied state information and executes asynchronously when the target Task completes and returns a value.

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

建立當目標 Task 完成並傳回值時非同步執行的接續。Creates a continuation that executes asynchronously when the target Task completes and returns a value. 接續會接收呼叫端提供的狀態資訊和取消語彙基元。The continuation receives caller-supplied state information and a cancellation token.

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

建立當目標 Task 完成並傳回值時,會根據指定的工作接續選項來執行的接續。Creates a continuation that executes based on the specified task continuation options when the target Task completes and returns a value. 接續會接收呼叫端提供的狀態資訊和取消語彙基元,並使用指定的排程器。The continuation receives caller-supplied state information and a cancellation token and uses the specified scheduler.

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

建立當目標 Task 完成時,會根據指定的工作接續選項來執行的接續。Creates a continuation that executes based on the specified task continuation options when the target Task completes. 接續會接收呼叫端提供的狀態資訊。The continuation receives caller-supplied state information.

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

建立當目標 Task 完成時非同步執行的接續。Creates a continuation that executes asynchronously when the target Task completes. 接續會接收呼叫端提供的狀態資訊,並使用指定的排程器。The continuation receives caller-supplied state information and uses a specified scheduler.

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

建立當目標 Task<TResult> 完成並傳回值時非同步執行的接續。Creates a continuation that executes asynchronously when the target Task<TResult> completes and returns a value.

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

建立當目標 Task 完成並傳回值時非同步執行的接續。Creates a continuation that executes asynchronously when the target Task completes and returns a value. 接續會接收取消語彙基元。The continuation receives a cancellation token.

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

建立會根據指定之接續選項執行並傳回值的接續。Creates a continuation that executes according to the specified continuation options and returns a value. 接續會接收取消語彙基元,並使用指定的排程器。The continuation is passed a cancellation token and uses a specified scheduler.

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

建立會根據指定之接續選項執行並傳回值的接續。Creates a continuation that executes according to the specified continuation options and returns a value.

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

建立當目標 Task 完成並傳回值時非同步執行的接續。Creates a continuation that executes asynchronously when the target Task completes and returns a value. 接續會使用指定的排程器。The continuation uses a specified scheduler.

Delay(Int32)

建立在指定的毫秒數之後完成的工作。Creates a task that completes after a specified number of milliseconds.

Delay(Int32, CancellationToken)

建立在指定的毫秒數之後完成的可取消工作。Creates a cancellable task that completes after a specified number of milliseconds.

Delay(TimeSpan)

建立在指定時間間隔之後完成的工作。Creates a task that completes after a specified time interval.

Delay(TimeSpan, CancellationToken)

建立在指定時間間隔之後完成的可取消工作。Creates a cancellable task that completes after a specified time interval.

Dispose()

釋放 Task 類別目前的執行個體所使用的全部資源。Releases all resources used by the current instance of the Task class.

Dispose(Boolean)

處置 Task,並釋放它的所有 Unmanaged 資源。Disposes the Task, releasing all of its unmanaged resources.

Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(繼承來源 Object)
FromCanceled(CancellationToken)

建立以指定的取消語彙基元取消而完成的 TaskCreates a Task that's completed due to cancellation with a specified cancellation token.

FromCanceled<TResult>(CancellationToken)

建立以指定的取消語彙基元取消而完成的 Task<TResult>Creates a Task<TResult> that's completed due to cancellation with a specified cancellation token.

FromException(Exception)

建立以指定例外狀況完成的 TaskCreates a Task that has completed with a specified exception.

FromException<TResult>(Exception)

建立以指定例外狀況完成的 Task<TResult>Creates a Task<TResult> that's completed with a specified exception.

FromResult<TResult>(TResult)

建立已成功完成具有指定之結果的 Task<TResult>Creates a Task<TResult> that's completed successfully with the specified result.

GetAwaiter()

取得用來等候這個 Task 的 awaiter。Gets an awaiter used to await this Task.

GetHashCode()

做為預設雜湊函式。Serves as the default hash function.

(繼承來源 Object)
GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(繼承來源 Object)
MemberwiseClone()

建立目前 Object 的淺層複本 (Shallow Copy)。Creates a shallow copy of the current Object.

(繼承來源 Object)
Run(Action)

將指定在執行緒集區執行工作排入佇列,並傳回代表該工作的 Task 物件。Queues the specified work to run on the thread pool and returns a Task object that represents that work.

Run(Action, CancellationToken)

將指定在執行緒集區執行工作排入佇列,並傳回代表該工作的 Task 物件。Queues the specified work to run on the thread pool and returns a Task object that represents that work. 取消語彙基元允許取消工作。A cancellation token allows the work to be cancelled.

Run(Func<Task>)

將指定在執行緒集區執行的工作排入佇列,並傳回 function 所傳回之工作的 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)

將指定在執行緒集區執行的工作排入佇列,並傳回 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>>)

將指定在執行緒集區執行的工作排入佇列,並傳回 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)

將指定在執行緒集區執行的工作排入佇列,並傳回 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>)

將指定在執行緒集區執行工作排入佇列,並傳回代表該工作的 Task<TResult> 物件。Queues the specified work to run on the thread pool and returns a Task<TResult> object that represents that work.

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

將指定在執行緒集區執行工作排入佇列,並傳回代表該工作的 Task(TResult) 物件。Queues the specified work to run on the thread pool and returns a Task(TResult) object that represents that work. 取消語彙基元允許取消工作。A cancellation token allows the work to be cancelled.

RunSynchronously()

在目前的 Task 上同步執行 TaskSchedulerRuns the Task synchronously on the current TaskScheduler.

RunSynchronously(TaskScheduler)

在提供的 Task 上同步執行 TaskSchedulerRuns the Task synchronously on the TaskScheduler provided.

Start()

啟動 Task,並排定它在目前的 TaskScheduler 執行。Starts the Task, scheduling it for execution to the current TaskScheduler.

Start(TaskScheduler)

啟動 Task,並排定它在指定的 TaskScheduler 執行。Starts the Task, scheduling it for execution to the specified TaskScheduler.

ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(繼承來源 Object)
Wait()

等候 Task 完成執行。Waits for the Task to complete execution.

Wait(CancellationToken)

等候 Task 完成執行。Waits for the Task to complete execution. 如果在工作完成之前取消語彙基元已取消,則等候會終止。The wait terminates if a cancellation token is canceled before the task completes.

Wait(Int32)

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

Wait(Int32, CancellationToken)

等候 Task 完成執行。Waits for the Task to complete execution. 如果在工作完成之前經過逾時間隔或取消語彙基元已取消,則等候會終止。The wait terminates if a timeout interval elapses or a cancellation token is canceled before the task completes.

Wait(TimeSpan)

等待 Task 在指定的時間間隔內完成執行。Waits for the Task to complete execution within a specified time interval.

WaitAll(Task[])

等候所有提供的 Task 物件完成執行。Waits for all of the provided Task objects to complete execution.

WaitAll(Task[], CancellationToken)

等候所有提供的 Task 物件完成執行。Waits for all of the provided Task objects to complete execution unless the wait is cancelled.

WaitAll(Task[], Int32)

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

WaitAll(Task[], Int32, CancellationToken)

等待所有提供的 Task 物件在指定的毫秒數內完成執行。Waits for all of the provided Task objects to complete execution within a specified number of milliseconds or until the wait is cancelled.

WaitAll(Task[], TimeSpan)

等候所有提供的可取消 Task 物件在指定的時間間隔內完成執行。Waits for all of the provided cancellable Task objects to complete execution within a specified time interval.

WaitAny(Task[])

等候任一提供的 Task 物件完成執行。Waits for any of the provided Task objects to complete execution.

WaitAny(Task[], CancellationToken)

等候所有提供的 Task 物件完成執行。Waits for any of the provided Task objects to complete execution unless the wait is cancelled.

WaitAny(Task[], Int32)

等候所有提供的 Task 物件在指定的毫秒數內完成執行。Waits for any of the provided Task objects to complete execution within a specified number of milliseconds.

WaitAny(Task[], Int32, CancellationToken)

等待所有提供的 Task 物件在指定的毫秒數內完成執行。Waits for any of the provided Task objects to complete execution within a specified number of milliseconds or until a cancellation token is cancelled.

WaitAny(Task[], TimeSpan)

等候其中任何一個提供的 Task 物件在指定的時間間隔內完成執行。Waits for any of the provided Task objects to complete execution within a specified time interval.

WhenAll(IEnumerable<Task>)

建立一個工作,當可列舉集合中的所有 Task 物件完成時,會完成此工作。Creates a task that will complete when all of the Task objects in an enumerable collection have completed.

WhenAll(Task[])

建立一個工作,當陣列中的所有 Task 物件完成時,會完成此工作。Creates a task that will complete when all of the Task objects in an array have completed.

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

建立一個工作,當可列舉集合中的所有 Task<TResult> 物件完成時,會完成此工作。Creates a task that will complete when all of the Task<TResult> objects in an enumerable collection have completed.

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

建立一個工作,當陣列中的所有 Task<TResult> 物件完成時,會完成此工作。Creates a task that will complete when all of the Task<TResult> objects in an array have completed.

WhenAny(IEnumerable<Task>)

建立當任一提供的工作完成時才會完成的工作。Creates a task that will complete when any of the supplied tasks have completed.

WhenAny(Task[])

建立當任一提供的工作完成時才會完成的工作。Creates a task that will complete when any of the supplied tasks have completed.

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

建立當任一提供的工作完成時才會完成的工作。Creates a task that will complete when any of the supplied tasks have completed.

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

建立當任一提供的工作完成時才會完成的工作。Creates a task that will complete when any of the supplied tasks have completed.

Yield()

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

明確介面實作

IAsyncResult.AsyncWaitHandle

取得 WaitHandle,這個項目可用來等候工作完成。Gets a WaitHandle that can be used to wait for the task to complete.

IAsyncResult.CompletedSynchronously

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

擴充方法

DispatcherOperationWait(Task)

無限期等候基礎 DispatcherOperation 完成。Waits indefinitely for the underlying DispatcherOperation to complete.

DispatcherOperationWait(Task, TimeSpan)

在指定的時間長度中等候,等候基礎 DispatcherOperation 完成。Waits for the specified amount of time for the underlying DispatcherOperation to complete.

IsDispatcherOperationTask(Task)

傳回值,表示這個 Task 是否與 DispatcherOperation 關聯。Returns a value that indicates whether this Task is associated with a DispatcherOperation.

AsAsyncAction(Task)

傳回代表已開始的動作的 Windows 執行階段非同步動作。Returns a Windows Runtime asynchronous action that represents a started task.

適用於

執行緒安全性

除了 Dispose() 以外,所有 Task 的成員都是安全線程,而且可以同時從多個執行緒使用。All members of Task, except for Dispose(), are thread-safe and may be used from multiple threads concurrently.

另請參閱