CancellationTokenSource 類別
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
發出 CancellationToken 應該取消的訊號。
public ref class CancellationTokenSource : IDisposable
public ref class CancellationTokenSource sealed : IDisposable
public class CancellationTokenSource : IDisposable
[System.Runtime.InteropServices.ComVisible(false)]
public sealed class CancellationTokenSource : IDisposable
[System.Runtime.InteropServices.ComVisible(false)]
public class CancellationTokenSource : IDisposable
type CancellationTokenSource = class
interface IDisposable
[<System.Runtime.InteropServices.ComVisible(false)>]
type CancellationTokenSource = class
interface IDisposable
Public Class CancellationTokenSource
Implements IDisposable
Public NotInheritable Class CancellationTokenSource
Implements IDisposable
- 繼承
-
CancellationTokenSource
- 屬性
- 實作
範例
下列範例會使用隨機數產生器來模擬數據收集應用程式,以從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.
備註
從 .NET Framework 4 開始,.NET Framework 會使用統一模型來合作取消包含兩個物件的異步或長時間執行的同步作業:
CancellationTokenSource 物件,透過其 Token 屬性提供取消令牌,並藉由呼叫其 Cancel 或 CancelAfter 方法來傳送取消訊息。
CancellationToken 物件,指出是否要求取消。
實作合作式取消模型的一般模式為:
具現化 CancellationTokenSource 物件,該物件會管理和傳送取消通知給個別的取消令牌。
將 CancellationTokenSource.Token 屬性傳回的令牌傳遞至接聽取消的每個工作或線程。
從接收取消令牌的作業呼叫 CancellationToken.IsCancellationRequested 方法。 為每個工作或線程提供一個機制,以回應取消要求。 無論您選擇取消作業,以及執行作業的方式,都取決於應用程式邏輯。
呼叫 CancellationTokenSource.Cancel 方法來提供取消通知。 這會將取消權杖的每個複本上的 CancellationToken.IsCancellationRequested 屬性設定為
true
。當您完成 CancellationTokenSource 物件時,請呼叫 Dispose 方法。
如需詳細資訊,請參閱在 Managed 線程中 取消。
重要
此類型會實作 IDisposable 介面。 當您使用 型別的實例完成時,應該直接或間接處置它。 若要直接處置類型,請在 try
/finally
區塊中呼叫其 Dispose 方法。 若要間接處置它,請使用語言建構,例如 using
(C#) 或 Using
(在 Visual Basic 中)。 如需詳細資訊,請參閱
建構函式
CancellationTokenSource() |
初始化 CancellationTokenSource 類別的新實例。 |
CancellationTokenSource(Int32) |
初始化 CancellationTokenSource 類別的新實例,這個實例將在指定的延遲以毫秒為單位後取消。 |
CancellationTokenSource(TimeSpan) |
初始化 CancellationTokenSource 類別的新實例,這個實例將在指定的時間範圍之後取消。 |
CancellationTokenSource(TimeSpan, TimeProvider) |
初始化 CancellationTokenSource 類別的新實例,這個實例將在指定的 TimeSpan之後取消。 |
屬性
IsCancellationRequested |
取得是否已為此 CancellationTokenSource要求取消。 |
Token |
取得與此 CancellationTokenSource相關聯的 CancellationToken。 |
方法
適用於
執行緒安全性
CancellationTokenSource 的所有公用和受保護成員都是安全線程,而且可以同時從多個線程使用,但 Dispose()除外,只有在 CancellationTokenSource 物件上所有其他作業都已完成時,才能使用。