CancellationTokenSource Classe

Definição

Sinaliza para um CancellationToken que ele deve ser cancelado.Signals to a CancellationToken that it should be canceled.

``public ref class CancellationTokenSource : IDisposable``
``````[System.Runtime.InteropServices.ComVisible(false)]
public class CancellationTokenSource : IDisposable``````
``````type CancellationTokenSource = class
interface IDisposable``````
``````Public Class CancellationTokenSource
Implements IDisposable``````
Herança
CancellationTokenSource
Atributos
Implementações

Exemplos

O exemplo a seguir usa um gerador de números aleatórios para emular um aplicativo de coleta de dados que lê 10 valores integrais de onze instrumentos diferentes.The following example uses a random number generator to emulate a data collection application that reads 10 integral values from eleven different instruments. Um valor de zero indica que a medição falhou para um instrumento; nesse caso, a operação deve ser cancelada e nenhuma média geral deve ser computada.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.

``````using System;
using System.Collections.Generic;

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();

int iteration = taskCtr + 1;
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();
break;
}
values[ctr-1] = value;
}
return values;
}, token));
}
try {
(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);
}
catch (AggregateException ae) {
foreach (Exception e in ae.InnerExceptions) {
Console.WriteLine("Unable to compute mean: {0}",
else
Console.WriteLine("Exception: " + e.GetType().Name);
}
}
finally {
source.Dispose();
}
}
}
// Repeated execution of the example produces output like the following:
//       Unable to compute mean: A task was canceled.
//
//       Unable to compute mean: A task was canceled.
//
//       Calculating overall mean...
//       The mean is 5.29545454545455.
//
//       Unable to compute mean: A task was canceled.
//
//       Unable to compute mean: A task was canceled.
//
//       Unable to compute mean: A task was canceled.
//
//       Calculating overall mean...
//       The mean is 4.97363636363636.
//
//       Unable to compute mean: A task was canceled.
//
//       Unable to compute mean: A task was canceled.
//
//       Unable to compute mean: A task was canceled.
//
//       Calculating overall mean...
//       The mean is 4.86545454545455.
``````
``````Imports System.Collections.Generic

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

For taskCtr As Integer = 0 To 10
Dim iteration As Integer = taskCtr + 1
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
Exit For
End If
values(ctr-1) = value
Next
Return values
End Function, token))

Next
Try
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)
Catch ae As AggregateException
For Each e In ae.InnerExceptions
Console.WriteLine("Unable to compute mean: {0}",
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:
'       Unable to compute mean: A task was canceled.
'
'       Unable to compute mean: A task was canceled.
'
'       Calculating overall mean...
'       The mean is 5.29545454545455.
'
'       Unable to compute mean: A task was canceled.
'
'       Unable to compute mean: A task was canceled.
'
'       Unable to compute mean: A task was canceled.
'
'       Calculating overall mean...
'       The mean is 4.97363636363636.
'
'       Unable to compute mean: A task was canceled.
'
'       Unable to compute mean: A task was canceled.
'
'       Unable to compute mean: A task was canceled.
'
'       Calculating overall mean...
'       The mean is 4.86545454545455.
``````

Comentários

A partir do .NET Framework 4.NET Framework 4, o .NET Framework usa um modelo unificado para o cancelamento cooperativo de operações síncronas ou síncronas de execução longa que envolvem dois objetos:Starting with the .NET Framework 4.NET Framework 4, the .NET Framework uses a unified model for cooperative cancellation of asynchronous or long-running synchronous operations that involves two objects:

O padrão geral para implementar o modelo de cancelamento cooperativo é:The general pattern for implementing the cooperative cancellation model is:

Importante

Esse tipo implementa a interface IDisposable.This type implements the IDisposable interface. Quando você terminar de usar uma instância do tipo, deverá descartá-la direta ou indiretamente.When you have finished using an instance of the type, you should dispose of it either directly or indirectly. Para descartar o tipo diretamente, chame o método Dispose dele em um bloco `try`/`catch`.To dispose of the type directly, call its Dispose method in a `try`/`catch` block. Para descartá-lo indiretamente, use um constructo de linguagem como `using` ( em C#) ou `Using` (em Visual Basic).To dispose of it indirectly, use a language construct such as `using` (in C#) or `Using` (in Visual Basic). Saiba mais na seção "Como usar um objeto que implementa IDisposable" no tópico da interface IDisposable.For more information, see the "Using an Object that Implements IDisposable" section in the IDisposable interface topic.

Construtores

 Inicializa uma nova instância da classe CancellationTokenSource.Initializes a new instance of the CancellationTokenSource class. Inicializa uma nova instância da classe CancellationTokenSource que será cancelada depois do atraso especificado em milissegundos.Initializes a new instance of the CancellationTokenSource class that will be canceled after the specified delay in milliseconds. Inicializa uma nova instância da classe CancellationTokenSource que será cancelada depois do intervalo de tempo especificado.Initializes a new instance of the CancellationTokenSource class that will be canceled after the specified time span.

 Especifica se foi solicitado cancelamento para essa CancellationTokenSource.Gets whether cancellation has been requested for this CancellationTokenSource. Obtém o CancellationToken associado a este CancellationTokenSource.Gets the CancellationToken associated with this CancellationTokenSource.