CancellationToken 结构
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
传播有关应取消操作的通知。
public value class CancellationToken
public value class CancellationToken : IEquatable<System::Threading::CancellationToken>
public struct CancellationToken
public readonly struct CancellationToken
public readonly struct CancellationToken : IEquatable<System.Threading.CancellationToken>
[System.Runtime.InteropServices.ComVisible(false)]
public struct CancellationToken
type CancellationToken = struct
[<System.Runtime.InteropServices.ComVisible(false)>]
type CancellationToken = struct
Public Structure CancellationToken
Public Structure CancellationToken
Implements IEquatable(Of 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 线程、线程池工作项或 Task 对象之间的协作取消。 通过实例化 CancellationTokenSource 对象来创建取消令牌,该对象管理从其属性检索到的 CancellationTokenSource.Token 取消令牌。 然后,将取消令牌传递给应收到取消通知的任何数量的线程、任务或操作。 令牌不能用于启动取消。 当拥有对象调用 CancellationTokenSource.Cancel时, IsCancellationRequested 取消令牌的每个副本上的属性将设置为 true
a0/>。 接收通知的对象可以以任何方式做出响应。
有关详细信息和代码示例,请参阅 托管线程中的取消。
构造函数
CancellationToken(Boolean) |
初始化 CancellationToken。 |
属性
CanBeCanceled |
获取此标记是否能处于已取消状态。 |
IsCancellationRequested |
获取是否已请求取消此标记。 |
None |
返回一个空 CancellationToken 值。 |
WaitHandle |
获取在取消标记时收到信号的 WaitHandle。 |
方法
Equals(CancellationToken) |
确定当前的 CancellationToken 实例是否等于指定的标记。 |
Equals(Object) |
确定当前的 CancellationToken 实例是否等于指定的 Object。 |
GetHashCode() |
作为 CancellationToken 的哈希函数。 |
Register(Action) |
注册一个将在取消此 CancellationToken 时调用的委托。 |
Register(Action, Boolean) |
注册一个将在取消此 CancellationToken 时调用的委托。 |
Register(Action<Object,CancellationToken>, Object) |
注册取消此 CancellationToken 时将调用的委托。 |
Register(Action<Object>, Object) |
注册一个将在取消此 CancellationToken 时调用的委托。 |
Register(Action<Object>, Object, Boolean) |
注册一个将在取消此 CancellationToken 时调用的委托。 |
ThrowIfCancellationRequested() |
如果已请求取消此标记,则引发 OperationCanceledException。 |
UnsafeRegister(Action<Object,CancellationToken>, Object) |
注册取消此 CancellationToken 时将调用的委托。 |
UnsafeRegister(Action<Object>, Object) |
注册一个在取消此 CancellationToken 时调用的委托。 |
运算符
Equality(CancellationToken, CancellationToken) |
确定两个 CancellationToken 实例是否相等。 |
Inequality(CancellationToken, CancellationToken) |
确定两个 CancellationToken 实例是否不相等。 |
适用于
线程安全性
所有公共成员和受保护成员 CancellationToken 都是线程安全的,并且可以从多个线程并发使用。