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)
- 繼承
- 屬性
- 實作
範例
下列範例會使用亂數產生器來模擬資料收集應用程式,以從十一個不同的檢測讀取 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
。 接收通知的物件可以適當地回應。
如需詳細資訊和程式碼範例,請參閱 Managed 執行緒中的取消。
建構函式
CancellationToken(Boolean) |
初始化 CancellationToken。 |
屬性
CanBeCanceled |
取得這個語彙基元是否能夠處於已取消狀態。 |
IsCancellationRequested |
取得是否已要求取消這個語彙基元。 |
None |
傳回空的 CancellationToken 值。 |
WaitHandle |
取得取消語彙基元時所發出的 WaitHandle 信號。 |
方法
Equals(CancellationToken) |
判斷目前的 CancellationToken 執行個體與指定的語彙基元是否相等。 |
Equals(Object) |
判斷目前的 CancellationToken 執行個體與指定的 Object 是否相等。 |
GetHashCode() |
做為 CancellationToken 的雜湊函式。 |
Register(Action, Boolean) |
註冊委派,當取消這個 CancellationToken 時將會呼叫該委派。 |
Register(Action) |
註冊委派,當取消這個 CancellationToken 時將會呼叫該委派。 |
Register(Action<Object,CancellationToken>, Object) |
註冊取消此 CancellationToken 時將會呼叫的委派。 |
Register(Action<Object>, Object, Boolean) |
註冊委派,當取消這個 CancellationToken 時將會呼叫該委派。 |
Register(Action<Object>, Object) |
註冊委派,當取消這個 CancellationToken 時將會呼叫該委派。 |
ThrowIfCancellationRequested() |
如果已要求取消這個語彙基元,則擲回 OperationCanceledException。 |
UnsafeRegister(Action<Object,CancellationToken>, Object) |
註冊取消此 CancellationToken 時將會呼叫的委派。 |
UnsafeRegister(Action<Object>, Object) |
註冊取消此 CancellationToken 時要呼叫的委派。 |
運算子
Equality(CancellationToken, CancellationToken) |
判斷兩個 CancellationToken 執行個體是否相等。 |
Inequality(CancellationToken, CancellationToken) |
判斷兩個 CancellationToken 執行個體是否不相等。 |
適用於
執行緒安全性
的所有公用和受保護成員 CancellationToken 都是安全線程,而且可以從多個執行緒同時使用。