CancellationTokenSource.Cancel 方法
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
传达取消请求。
重载
Cancel() |
传达取消请求。 |
Cancel(Boolean) |
如果出现异常,传达取消请求,并指定是否应处理其余回调和可取消操作。 |
Cancel()
传达取消请求。
public:
void Cancel();
public void Cancel ();
member this.Cancel : unit -> unit
Public Sub Cancel ()
例外
聚合异常包含由相关联的 CancellationToken 上已注册的回调引发的所有异常。
示例
以下示例使用随机数生成器模拟从 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.
注解
关联的 CancellationToken 通知将通知取消,并将转换为返回 IsCancellationRequested true 的状态。
将执行注册到该 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通知将通知取消,并将转换为返回IsCancellationRequestedtrue
的状态。
将执行注册到该 CancellationToken 操作的任何回调或可取消操作。 回调将以 LIFO 顺序同步执行。
建议取消注册且 CancellationToken 未引发异常的操作和回调。
true
如果是throwOnFirstException
,异常将立即传播到调用Cancel之外,从而阻止处理剩余回调和可取消操作。
false
如果是throwOnFirstException
,此重载将聚合引发到某个AggregateException异常的任何异常,这样一个引发异常的回调就不会阻止执行其他已注册的回调。