Cet article a fait l’objet d’une traduction automatique. Pour afficher l’article en anglais, activez la case d’option Anglais. Vous pouvez également afficher le texte anglais dans une fenêtre contextuelle en faisant glisser le pointeur de la souris sur le texte traduit.
Traduction
Anglais

CancellationTokenSource classe

 

Date de publication : novembre 2016

Signale à un CancellationToken qu'il doit être annulé.

Espace de noms:   System.Threading
Assembly:  mscorlib (dans mscorlib.dll)

System.Object
  System.Threading.CancellationTokenSource

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

NomDescription
System_CAPS_pubmethodCancellationTokenSource()

Initialise une nouvelle instance de la classe CancellationTokenSource.

System_CAPS_pubmethodCancellationTokenSource(Int32)

Initialise une nouvelle instance de la classe CancellationTokenSource qui sera annulée après le délai spécifié en millisecondes.

System_CAPS_pubmethodCancellationTokenSource(TimeSpan)

Initialise une nouvelle instance de la classe CancellationTokenSource qui sera annulée après l'intervalle de temps spécifié.

NomDescription
System_CAPS_pubpropertyIsCancellationRequested

Détermine si l'annulation a été demandée pour cette CancellationTokenSource.

System_CAPS_pubpropertyToken

Obtient l'CancellationToken associée à cette CancellationTokenSource.

NomDescription
System_CAPS_pubmethodCancel()

Transmet une demande d'annulation.

System_CAPS_pubmethodCancel(Boolean)

Transmet une demande d'annulation, et spécifie si les rappels restants et les opérations annulables doivent être traités.

System_CAPS_pubmethodCancelAfter(Int32)

Planifie une opération d'annulation sur cette CancellationTokenSource après le nombre spécifié de millisecondes.

System_CAPS_pubmethodCancelAfter(TimeSpan)

Planifie une opération d'annulation sur cette CancellationTokenSource après l'intervalle de temps spécifié.

System_CAPS_pubmethodSystem_CAPS_staticCreateLinkedTokenSource(CancellationToken, CancellationToken)

Crée une CancellationTokenSource qui est à l'état annulé quand l'un des jetons source est à l'état annulé.

System_CAPS_pubmethodSystem_CAPS_staticCreateLinkedTokenSource(CancellationToken[])

Crée une CancellationTokenSource qui est à l'état « annulé » quand l'un des jetons sources du tableau spécifié est à l'état « annulé ».

System_CAPS_pubmethodDispose()

Libère toutes les ressources utilisées par l'instance actuelle de la classe CancellationTokenSource.

System_CAPS_protmethodDispose(Boolean)

Libère les ressources non managées utilisées par la classe CancellationTokenSource et libère éventuellement les ressources managées.

System_CAPS_pubmethodEquals(Object)

Détermine si l'objet spécifié est identique à l'objet actuel.(Hérité de Object.)

System_CAPS_protmethodFinalize()

Autorise un objet à tenter de libérer des ressources et d'exécuter d'autres opérations de nettoyage avant qu'il ne soit récupéré par l'opération garbage collection. (Hérité de Object.)

System_CAPS_pubmethodGetHashCode()

Fait office de fonction de hachage par défaut.(Hérité de Object.)

System_CAPS_pubmethodGetType()

Obtient le Type de l'instance actuelle.(Hérité de Object.)

System_CAPS_protmethodMemberwiseClone()

Crée une copie superficielle du Object actuel.(Hérité de Object.)

System_CAPS_pubmethodToString()

Retourne une chaîne qui représente l'objet actuel.(Hérité 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_importantImportant

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.

Plateforme Windows universelle
Disponible depuis 8
.NET Framework
Disponible depuis 4.0
Bibliothèque de classes portable
Pris en charge dans : plateformes .NET portables
Silverlight
Disponible depuis 5.0
Silverlight pour Windows Phone
Disponible depuis 8.0
Windows Phone
Disponible depuis 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.

Retour au début
Afficher: