Este artículo se tradujo automáticamente. Para ver el artículo en inglés, active la casilla Inglés. Además, puede mostrar el texto en inglés en una ventana emergente si mueve el puntero del mouse sobre el texto.
Traducción
Inglés

Clase CancellationTokenSource

 

Publicado: octubre de 2016

Señala un objeto CancellationToken que debe cancelarse.

Espacio de nombres:   System.Threading
Ensamblado:  mscorlib (en mscorlib.dll)

System.Object
  System.Threading.CancellationTokenSource

[ComVisibleAttribute(false)]
[HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization = true, 
	ExternalThreading = true)]
public class CancellationTokenSource : IDisposable

NombreDescripción
System_CAPS_pubmethodCancellationTokenSource()

Inicializa una nueva instancia de la clase CancellationTokenSource.

System_CAPS_pubmethodCancellationTokenSource(Int32)

Inicializa una nueva instancia de la clase CancellationTokenSource que se cancela después del retraso especificado en milisegundos.

System_CAPS_pubmethodCancellationTokenSource(TimeSpan)

Inicializa una nueva instancia de la clase CancellationTokenSource que se cancela después del intervalo de tiempo especificado.

NombreDescripción
System_CAPS_pubpropertyIsCancellationRequested

Obtiene si se solicitó la cancelación de este CancellationTokenSource.

System_CAPS_pubpropertyToken

Obtiene el objeto CancellationToken asociado a CancellationTokenSource.

NombreDescripción
System_CAPS_pubmethodCancel()

Comunica una solicitud de cancelación.

System_CAPS_pubmethodCancel(Boolean)

Comunica una solicitud de cancelación y especifica si se deben procesar las devoluciones de llamada restantes y las operaciones cancelables.

System_CAPS_pubmethodCancelAfter(Int32)

Programa una operación de cancelación en este CancellationTokenSource después del número especificado de milisegundos.

System_CAPS_pubmethodCancelAfter(TimeSpan)

Programa una operación de cancelación en este CancellationTokenSource después del intervalo de tiempo especificado.

System_CAPS_pubmethodSystem_CAPS_staticCreateLinkedTokenSource(CancellationToken, CancellationToken)

Crea un CancellationTokenSource que tendrá el estado cancelado cuando alguno de los tokens de origen tenga el estado cancelado.

System_CAPS_pubmethodSystem_CAPS_staticCreateLinkedTokenSource(CancellationToken[])

Crea un CancellationTokenSource que tendrá el estado cancelado cuando alguno de los tokens de origen del la matriz especificada tenga el estado cancelado.

System_CAPS_pubmethodDispose()

Libera todos los recursos usados por la instancia actual de la clase CancellationTokenSource.

System_CAPS_protmethodDispose(Boolean)

Libera los recursos no administrados usados que usa la clase CancellationTokenSource y, de forma opcional, libera los recursos administrados.

System_CAPS_pubmethodEquals(Object)

Determina si el objeto especificado es igual al objeto actual.(Heredado de Object).

System_CAPS_protmethodFinalize()

Permite que un objeto intente liberar recursos y realizar otras operaciones de limpieza antes de ser reclamado por el recolector de basura. (Heredado de Object).

System_CAPS_pubmethodGetHashCode()

Sirve como la función hash predeterminada.(Heredado de Object).

System_CAPS_pubmethodGetType()

Obtiene el Type de la instancia actual.(Heredado de Object).

System_CAPS_protmethodMemberwiseClone()

Crea una copia superficial del Object actual.(Heredado de Object).

System_CAPS_pubmethodToString()

Devuelve una cadena que representa al objeto actual. (Heredado de Object).

Starting with the net_v40_long, the .NET Framework uses a unified model for cooperative cancellation of asynchronous or long-running synchronous operations that involves two objects:

  • A T:System.Threading.CancellationTokenSource object, which provides a cancellation token through its P:System.Threading.CancellationTokenSource.Token property and sends a cancellation message by calling its M:System.Threading.CancellationTokenSource.Cancel or M:System.Threading.CancellationTokenSource.CancelAfter(System.Int32) method.

  • A T:System.Threading.CancellationToken object, which indicates whether cancellation is requested.

The general pattern for implementing the cooperative cancellation model is:

  • Instantiate a T:System.Threading.CancellationTokenSource object, which manages and sends cancellation notification to the individual cancellation tokens.

  • Pass the token returned by the P:System.Threading.CancellationTokenSource.Token property to each task or thread that listens for cancellation.

  • Call the P:System.Threading.CancellationToken.IsCancellationRequested method from operations that receive the cancellation token. Provide a mechanism for each task or thread to respond to a cancellation request. Whether you choose to cancel an operation, and exactly how you do it, depends on your application logic.

  • Call the M:System.Threading.CancellationTokenSource.Cancel(System.Boolean) method to provide notification of cancellation. This sets the P:System.Threading.CancellationToken.IsCancellationRequested property on every copy of the cancellation token to true.

  • Call the M:System.Threading.CancellationTokenSource.Dispose method when you are finished with the T:System.Threading.CancellationTokenSource object.

For more information, see Cancellation.

System_CAPS_importantImportante

This type implements the T:System.IDisposable interface. When you have finished using an instance of the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its M:System.IDisposable.Dispose method in a try/catch block. To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic). For more information, see the “Using an Object that Implements IDisposable” section in the T:System.IDisposable interface topic.

The following example uses a random number generator to emulate a data collection application that reads 10 integral values from eleven different instruments. 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.

To handle the possible cancellation of the operation, the example instantiates a T:System.Threading.CancellationTokenSource object that generates a cancellation token which is passed to a T:System.Threading.Tasks.TaskFactory object. The T:System.Threading.Tasks.TaskFactory object in turn passes the cancellation token to each of the tasks responsible for collecting readings for a particular instrument. The M:System.Threading.Tasks.TaskFactory.ContinueWhenAll``2(System.Threading.Tasks.Task{``0}[],System.Func{System.Threading.Tasks.Task{``0}[],``1},System.Threading.CancellationToken) method is called to ensure that the mean is computed only after all readings have been gathered successfully. If a task has not because it has been cancelled, the call to the M:System.Threading.Tasks.TaskFactory.ContinueWhenAll``2(System.Threading.Tasks.Task{``0}[],System.Func{System.Threading.Tasks.Task{``0}[],``1},System.Threading.CancellationToken) method throws an exception.

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.

Plataforma universal de Windows
Disponible desde 8
.NET Framework
Disponible desde 4.0
Biblioteca de clases portable
Se admite en: plataformas portátiles de .NET
Silverlight
Disponible desde 5.0
Windows Phone Silverlight
Disponible desde 8.0
Windows Phone
Disponible desde 8.1

All public and protected members of T:System.Threading.CancellationTokenSource are thread-safe and may be used concurrently from multiple threads, with the exception of M:System.Threading.CancellationTokenSource.Dispose, which must only be used when all other operations on the T:System.Threading.CancellationTokenSource object have completed.

Volver al principio
Mostrar: