共用方式為


CancellationTokenSource 類別

定義

發出 CancellationToken 應該取消的訊號。

public ref class CancellationTokenSource : IDisposable
public ref class CancellationTokenSource sealed : IDisposable
public class CancellationTokenSource : IDisposable
[System.Runtime.InteropServices.ComVisible(false)]
public sealed class CancellationTokenSource : IDisposable
[System.Runtime.InteropServices.ComVisible(false)]
public class CancellationTokenSource : IDisposable
type CancellationTokenSource = class
    interface IDisposable
[<System.Runtime.InteropServices.ComVisible(false)>]
type CancellationTokenSource = class
    interface IDisposable
Public Class CancellationTokenSource
Implements IDisposable
Public NotInheritable Class CancellationTokenSource
Implements IDisposable
繼承
CancellationTokenSource
屬性
實作

範例

下列範例會使用隨機數產生器來模擬數據收集應用程式,以從11個不同儀器讀取10個整數值。 值為零表示一個儀器的測量失敗,在此情況下應該取消作業,而且不應計算整體平均數。

為了處理作業的可能取消作業,此範例會具現化 CancellationTokenSource 對象,這個物件會產生傳遞至 TaskFactory 物件的取消標記。 TaskFactory 對象接著會將取消標記傳遞給負責收集特定儀器讀數的每個工作。 呼叫 TaskFactory.ContinueWhenAll<TAntecedentResult,TResult>(Task<TAntecedentResult>[], Func<Task<TAntecedentResult>[],TResult>, CancellationToken) 方法,以確保只有在成功收集所有讀數之後,才會計算平均值。 如果工作因為已取消而尚未完成,則呼叫 TaskFactory.ContinueWhenAll 方法會擲回例外狀況。

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      // Define the cancellation token.
      CancellationTokenSource source = new CancellationTokenSource();
      CancellationToken token = source.Token;

      Random rnd = new Random();
      Object lockObj = new Object();
      
      List<Task<int[]>> tasks = new List<Task<int[]>>();
      TaskFactory factory = new TaskFactory(token);
      for (int taskCtr = 0; taskCtr <= 10; taskCtr++) {
         int iteration = taskCtr + 1;
         tasks.Add(factory.StartNew( () => {
           int value;
           int[] values = new int[10];
           for (int ctr = 1; ctr <= 10; ctr++) {
              lock (lockObj) {
                 value = rnd.Next(0,101);
              }
              if (value == 0) { 
                 source.Cancel();
                 Console.WriteLine("Cancelling at task {0}", iteration);
                 break;
              }   
              values[ctr-1] = value; 
           }
           return values;
        }, token));   
      }
      try {
         Task<double> fTask = factory.ContinueWhenAll(tasks.ToArray(), 
         (results) => {
            Console.WriteLine("Calculating overall mean...");
            long sum = 0;
            int n = 0; 
            foreach (var t in results) {
               foreach (var r in t.Result) {
                  sum += r;
                  n++;
               }
            }
            return sum/(double) n;
         } , token);
         Console.WriteLine("The mean is {0}.", fTask.Result);
      }   
      catch (AggregateException ae) {
         foreach (Exception e in ae.InnerExceptions) {
            if (e is TaskCanceledException)
               Console.WriteLine("Unable to compute mean: {0}", 
                  ((TaskCanceledException) e).Message);
            else
               Console.WriteLine("Exception: " + e.GetType().Name);
         }
      }
      finally {
         source.Dispose();
      }
   }
}
// Repeated execution of the example produces output like the following:
//       Cancelling at task 5
//       Unable to compute mean: A task was canceled.
//       
//       Cancelling at task 10
//       Unable to compute mean: A task was canceled.
//       
//       Calculating overall mean...
//       The mean is 5.29545454545455.
//       
//       Cancelling at task 4
//       Unable to compute mean: A task was canceled.
//       
//       Cancelling at task 5
//       Unable to compute mean: A task was canceled.
//       
//       Cancelling at task 6
//       Unable to compute mean: A task was canceled.
//       
//       Calculating overall mean...
//       The mean is 4.97363636363636.
//       
//       Cancelling at task 4
//       Unable to compute mean: A task was canceled.
//       
//       Cancelling at task 5
//       Unable to compute mean: A task was canceled.
//       
//       Cancelling at task 4
//       Unable to compute mean: A task was canceled.
//       
//       Calculating overall mean...
//       The mean is 4.86545454545455.
Imports System.Collections.Generic
Imports System.Threading
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      ' Define the cancellation token.
      Dim source As New CancellationTokenSource()
      Dim token As CancellationToken = source.Token

      Dim lockObj As New Object()
      Dim rnd As New Random

      Dim tasks As New List(Of Task(Of Integer()))
      Dim factory As New TaskFactory(token)
      For taskCtr As Integer = 0 To 10
         Dim iteration As Integer = taskCtr + 1
         tasks.Add(factory.StartNew(Function()
                                       Dim value, values(9) As Integer
                                       For ctr As Integer = 1 To 10
                                          SyncLock lockObj
                                             value = rnd.Next(0,101)
                                          End SyncLock
                                          If value = 0 Then 
                                             source.Cancel
                                             Console.WriteLine("Cancelling at task {0}", iteration)
                                             Exit For
                                          End If   
                                          values(ctr-1) = value 
                                       Next
                                       Return values
                                    End Function, token))   
         
      Next
      Try
         Dim fTask As Task(Of Double) = factory.ContinueWhenAll(tasks.ToArray(), 
                                                         Function(results)
                                                            Console.WriteLine("Calculating overall mean...")
                                                            Dim sum As Long
                                                            Dim n As Integer 
                                                            For Each t In results
                                                               For Each r In t.Result
                                                                  sum += r
                                                                  n+= 1
                                                               Next
                                                            Next
                                                            Return sum/n
                                                         End Function, token)
         Console.WriteLine("The mean is {0}.", fTask.Result)
      Catch ae As AggregateException
         For Each e In ae.InnerExceptions
            If TypeOf e Is TaskCanceledException
               Console.WriteLine("Unable to compute mean: {0}", 
                                 CType(e, TaskCanceledException).Message)
            Else
               Console.WriteLine("Exception: " + e.GetType().Name)
            End If   
         Next
      Finally
         source.Dispose()
      End Try                                                          
   End Sub
End Module
' Repeated execution of the example produces output like the following:
'       Cancelling at task 5
'       Unable to compute mean: A task was canceled.
'       
'       Cancelling at task 10
'       Unable to compute mean: A task was canceled.
'       
'       Calculating overall mean...
'       The mean is 5.29545454545455.
'       
'       Cancelling at task 4
'       Unable to compute mean: A task was canceled.
'       
'       Cancelling at task 5
'       Unable to compute mean: A task was canceled.
'       
'       Cancelling at task 6
'       Unable to compute mean: A task was canceled.
'       
'       Calculating overall mean...
'       The mean is 4.97363636363636.
'       
'       Cancelling at task 4
'       Unable to compute mean: A task was canceled.
'       
'       Cancelling at task 5
'       Unable to compute mean: A task was canceled.
'       
'       Cancelling at task 4
'       Unable to compute mean: A task was canceled.
'       
'       Calculating overall mean...
'       The mean is 4.86545454545455.

備註

從 .NET Framework 4 開始,.NET Framework 會使用統一模型來合作取消包含兩個物件的異步或長時間執行的同步作業:

實作合作式取消模型的一般模式為:

如需詳細資訊,請參閱在 Managed 線程中 取消

重要

此類型會實作 IDisposable 介面。 當您使用 型別的實例完成時,應該直接或間接處置它。 若要直接處置類型,請在 try/finally 區塊中呼叫其 Dispose 方法。 若要間接處置它,請使用語言建構,例如 using (C#) 或 Using (在 Visual Basic 中)。 如需詳細資訊,請參閱 介面主題中的<使用實作 IDisposable 的物件>一節。

建構函式

CancellationTokenSource()

初始化 CancellationTokenSource 類別的新實例。

CancellationTokenSource(Int32)

初始化 CancellationTokenSource 類別的新實例,這個實例將在指定的延遲以毫秒為單位後取消。

CancellationTokenSource(TimeSpan)

初始化 CancellationTokenSource 類別的新實例,這個實例將在指定的時間範圍之後取消。

CancellationTokenSource(TimeSpan, TimeProvider)

初始化 CancellationTokenSource 類別的新實例,這個實例將在指定的 TimeSpan之後取消。

屬性

IsCancellationRequested

取得是否已為此 CancellationTokenSource要求取消。

Token

取得與此 CancellationTokenSource相關聯的 CancellationToken

方法

Cancel()

傳達取消的要求。

Cancel(Boolean)

傳達取消的要求,並指定例外狀況發生時,是否應該處理剩餘的回呼和可取消的作業。

CancelAfter(Int32)

在指定的毫秒數之後,排程此 CancellationTokenSource 取消作業。

CancelAfter(TimeSpan)

在指定的時間範圍之後,排程此 CancellationTokenSource 上的取消作業。

CancelAsync()

以異步方式傳達取消的要求。

CreateLinkedTokenSource(CancellationToken)

建立 CancellationTokenSource,當提供的令牌處於已取消狀態時,將會處於取消狀態。

CreateLinkedTokenSource(CancellationToken, CancellationToken)

建立 CancellationTokenSource,當任何來源令牌處於取消狀態時,都會處於取消狀態。

CreateLinkedTokenSource(CancellationToken[])

建立 CancellationTokenSource,當指定數位中的任何來源令牌處於取消狀態時,將會處於取消狀態。

CreateLinkedTokenSource(ReadOnlySpan<CancellationToken>)

建立 CancellationTokenSource,當任何來源令牌處於取消狀態時,都會處於取消狀態。

Dispose()

釋放目前 CancellationTokenSource 類別實例所使用的所有資源。

Dispose(Boolean)

釋放 CancellationTokenSource 類別所使用的 Unmanaged 資源,並選擇性地釋放 Managed 資源。

Equals(Object)

判斷指定的物件是否等於目前的物件。

(繼承來源 Object)
GetHashCode()

做為預設哈希函式。

(繼承來源 Object)
GetType()

取得目前實例的 Type

(繼承來源 Object)
MemberwiseClone()

建立目前 Object的淺層複本。

(繼承來源 Object)
ToString()

傳回表示目前 物件的字串。

(繼承來源 Object)
TryReset()

嘗試重設 CancellationTokenSource,以用於不相關的作業。

適用於

執行緒安全性

CancellationTokenSource 的所有公用和受保護成員都是安全線程,而且可以同時從多個線程使用,但 Dispose()除外,只有在 CancellationTokenSource 物件上所有其他作業都已完成時,才能使用。

另請參閱