共用方式為


CancellationTokenSource.Cancel 方法

定義

傳遞取消要求。

多載

Cancel()

傳遞取消要求。

Cancel(Boolean)

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

Cancel()

傳遞取消要求。

public:
 void Cancel();
public void Cancel ();
member this.Cancel : unit -> unit
Public Sub Cancel ()

例外狀況

包含所有由相關聯的 CancellationToken 上已註冊的回呼所擲回例外狀況的彙總例外狀況。

範例

下列範例會使用亂數產生器來模擬從十一個不同檢測讀取 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.

備註

相關聯的 CancellationToken 將會收到取消通知,並轉換為傳回 true 的狀態 IsCancellationRequested

將會執行向 CancellationToken 註冊的任何回呼或可取消作業。

我們建議取消的作業和回呼註冊, CancellationToken 但不會擲回例外狀況。

Cancel 的這個多載會將擲回的任何例外狀況匯總到 AggregateException ,如此一個擲回例外狀況的回呼將不會防止執行其他已註冊的回呼。

呼叫這個方法的效果與呼叫 Cancel(false) 相同。

另請參閱

適用於

Cancel(Boolean)

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

public:
 void Cancel(bool throwOnFirstException);
public void Cancel (bool throwOnFirstException);
member this.Cancel : bool -> unit
Public Sub Cancel (throwOnFirstException As Boolean)

參數

throwOnFirstException
Boolean

如果應該立即散佈例外狀況則為 true,否則為 false

例外狀況

包含所有由相關聯的 CancellationToken 上已註冊的回呼所擲回例外狀況的彙總例外狀況。

備註

相關聯的 CancellationToken 將會收到取消通知,並轉換為傳回 true 的狀態 IsCancellationRequested

將會執行向 CancellationToken 註冊的任何回呼或可取消作業。 回呼會以 LIFO 順序同步執行。

我們建議取消的作業和回呼註冊, CancellationToken 但不會擲回例外狀況。

如果 為 throwOnFirstException true ,例外狀況會立即傳播至 的呼叫 Cancel ,以防止處理其餘的回呼和可取消的作業。

如果 throwOnFirstExceptionfalse ,此多載會將擲回的任何例外狀況匯總到 AggregateException ,如此一個擲回例外狀況的回呼將不會防止執行其他已註冊的回呼。

另請參閱

適用於