CancellationTokenSource.Cancel 方法

定義

傳遞取消要求。Communicates a request for cancellation.

多載

Cancel()

傳遞取消要求。Communicates a request for cancellation.

Cancel(Boolean)

傳遞取消要求,並指定如果發生例外狀況時,是否應處理其餘回呼和可取消的作業。Communicates a request for cancellation, and specifies whether remaining callbacks and cancelable operations should be processed if an exception occurs.

Cancel()

傳遞取消要求。Communicates a request for cancellation.

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

例外狀況

已經處置這個 CancellationTokenSourceThis CancellationTokenSource has been disposed.

包含所有由相關聯的 CancellationToken 上已註冊的回呼所擲回例外狀況的彙總例外狀況。An aggregate exception containing all the exceptions thrown by the registered callbacks on the associated CancellationToken.

範例

下列範例會使用亂數產生器來模擬資料收集應用程式,以從11個不同的儀器讀取10個整數值。The following example uses a random number generator to emulate a data collection application that reads 10 integral values from eleven different instruments. 值為零表示某個檢測的度量失敗,在此情況下,應該取消作業,而且不會計算整體平均值。A value of zero indicates that the measurement has failed for one instrument, in which case the operation should be cancelled and no overall mean should be computed.

為了處理作業的可能取消作業,此範例會具現化 CancellationTokenSource 物件,以產生傳遞給 TaskFactory 物件的解除標記。To handle the possible cancellation of the operation, the example instantiates a CancellationTokenSource object that generates a cancellation token which is passed to a TaskFactory object. TaskFactory 物件接著會將解除標記傳遞給負責收集特定檢測之讀取的每個工作。The TaskFactory object in turn passes the cancellation token to each of the tasks responsible for collecting readings for a particular instrument. 呼叫 TaskFactory.ContinueWhenAll<TAntecedentResult,TResult>(Task<TAntecedentResult>[], Func<Task<TAntecedentResult>[],TResult>, CancellationToken) 方法,以確保只有在成功收集所有讀數之後,才會計算平均值。The TaskFactory.ContinueWhenAll<TAntecedentResult,TResult>(Task<TAntecedentResult>[], Func<Task<TAntecedentResult>[],TResult>, CancellationToken) method is called to ensure that the mean is computed only after all readings have been gathered successfully. 如果工作尚未被取消,則呼叫 TaskFactory.ContinueWhenAll 方法會擲回例外狀況。If a task has not because it has been cancelled, the call to the TaskFactory.ContinueWhenAll method throws an exception.

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 將會收到取消通知,並會轉換成 IsCancellationRequested 傳回 true 的狀態。The associated CancellationToken will be notified of the cancellation and will transition to a state where IsCancellationRequested returns true.

將會執行任何向 CancellationToken 註冊的回呼或可取消作業。Any callbacks or cancelable operations registered with the CancellationToken will be executed.

我們建議您在 CancellationToken 中註冊可取消的作業和回呼,而不會擲回例外狀況。We recommend that cancelable operations and callbacks registered with CancellationToken not throw exceptions.

這個取消的多載會將擲回的任何例外狀況匯總到 AggregateException中,因此擲回例外狀況的一個回呼將無法防止執行其他已註冊的回呼。This overload of Cancel will aggregate any exceptions thrown into an AggregateException, such that one callback throwing an exception will not prevent other registered callbacks from being executed.

另請參閱

Cancel(Boolean)

傳遞取消要求,並指定如果發生例外狀況時,是否應處理其餘回呼和可取消的作業。Communicates a request for cancellation, and specifies whether remaining callbacks and cancelable operations should be processed if an exception occurs.

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

參數

throwOnFirstException
Boolean

如果應該立即散佈例外狀況則為 true,否則為 falsetrue if exceptions should immediately propagate; otherwise, false.

例外狀況

已經處置這個 CancellationTokenSourceThis CancellationTokenSource has been disposed.

包含所有由相關聯的 CancellationToken 上已註冊的回呼所擲回例外狀況的彙總例外狀況。An aggregate exception containing all the exceptions thrown by the registered callbacks on the associated CancellationToken.

備註

相關聯的 CancellationToken 將會收到取消通知,並會轉換成 IsCancellationRequested 傳回 true的狀態。The associated CancellationToken will be notified of the cancellation and will transition to a state where IsCancellationRequested returns true.

將會執行任何向 CancellationToken 註冊的回呼或可取消作業。Any callbacks or cancelable operations registered with the CancellationToken will be executed. 回呼會以 LIFO 順序以同步方式執行。Callbacks will be executed synchronously in LIFO order.

我們建議您在 CancellationToken 中註冊可取消的作業和回呼,而不會擲回例外狀況。We recommend that cancelable operations and callbacks registered with CancellationToken not throw exceptions.

如果 true``throwOnFirstException,例外狀況會立即傳播至 Cancel的呼叫,以防止處理其餘的回呼和可取消的作業。If throwOnFirstException is true, an exception will immediately propagate out of the call to Cancel, preventing the remaining callbacks and cancelable operations from being processed.

如果 false``throwOnFirstException,此多載會將擲回的任何例外狀況匯總至 AggregateException,因此擲回例外狀況的一個回呼將無法防止執行其他已註冊的回呼。If throwOnFirstException is false, this overload will aggregate any exceptions thrown into an AggregateException, such that one callback throwing an exception will not prevent other registered callbacks from being executed.

另請參閱

適用於