Suspension et interruption de threadsPausing and interrupting threads

Les méthodes les plus courantes permettant de synchroniser les activités de threads consistent à bloquer et à diffuser des threads, ou à verrouiller des objets ou des régions du code.The most common ways to synchronize the activities of threads are to block and release threads, or to lock objects or regions of code. Pour plus d’informations sur ces mécanismes de verrouillage et de blocage, voir Vue d’ensemble des primitives de synchronisation.For more information on these locking and blocking mechanisms, see Overview of Synchronization Primitives.

Vous pouvez également avoir des threads en veille.You can also have threads put themselves to sleep. Quand des threads sont bloqués ou en veille, vous pouvez utiliser une ThreadInterruptedException pour les débloquer ou les réveiller.When threads are blocked or sleeping, you can use a ThreadInterruptedException to break them out of their wait states.

La méthode Thread.SleepThe Thread.Sleep method

L'appel de la méthode Thread.Sleep entraîne le blocage immédiat du thread actuel pendant le nombre de millisecondes ou l’intervalle de temps que dure le passage à la méthode et cède le reste de sa tranche horaire à un autre thread.Calling the Thread.Sleep method causes the current thread to immediately block for the number of milliseconds or the time interval you pass to the method, and yields the remainder of its time slice to another thread. Une fois l’intervalle expiré, l’exécution du thread en veille reprend.Once that interval elapses, the sleeping thread resumes execution.

Un thread ne peut pas appeler Thread.Sleep sur un autre thread.One thread cannot call Thread.Sleep on another thread. Thread.Sleep est une méthode statique qui entraîne systématiquement la mise en veille du thread actuel.Thread.Sleep is a static method that always causes the current thread to sleep.

L'appel de Thread.Sleep avec une valeur de Timeout.Infinite entraîne la mise en veille du thread jusqu'à ce qu'elle soit interrompue par un autre thread qui appelle la méthode Thread.Interrupt, ou jusqu'à ce qu'elle soit terminée par un appel à sa méthode Thread.Abort.Calling Thread.Sleep with a value of Timeout.Infinite causes a thread to sleep until it is interrupted by another thread that calls the Thread.Interrupt method on the sleeping thread, or until it is terminated by a call to its Thread.Abort method. L’exemple suivant illustre les deux méthodes d’interruption d’un thread en veille.The following example illustrates both methods of interrupting a sleeping thread.

using System;
using System.Threading;

public class Example
{
   public static void Main()
   {
      // Interrupt a sleeping thread.
      var sleepingThread = new Thread(Example.SleepIndefinitely);
      sleepingThread.Name = "Sleeping";
      sleepingThread.Start();
      Thread.Sleep(2000);
      sleepingThread.Interrupt();

      Thread.Sleep(1000);

      sleepingThread = new Thread(Example.SleepIndefinitely);
      sleepingThread.Name = "Sleeping2";
      sleepingThread.Start();
      Thread.Sleep(2000);
      sleepingThread.Abort();
   }

   private static void SleepIndefinitely()
   {
      Console.WriteLine("Thread '{0}' about to sleep indefinitely.",
                        Thread.CurrentThread.Name);
      try {
         Thread.Sleep(Timeout.Infinite);
      }
      catch (ThreadInterruptedException) {
         Console.WriteLine("Thread '{0}' awoken.",
                           Thread.CurrentThread.Name);
      }
      catch (ThreadAbortException) {
         Console.WriteLine("Thread '{0}' aborted.",
                           Thread.CurrentThread.Name);
      }
      finally
      {
         Console.WriteLine("Thread '{0}' executing finally block.",
                           Thread.CurrentThread.Name);
      }
      Console.WriteLine("Thread '{0} finishing normal execution.",
                        Thread.CurrentThread.Name);
      Console.WriteLine();
   }
}
// The example displays the following output:
//       Thread 'Sleeping' about to sleep indefinitely.
//       Thread 'Sleeping' awoken.
//       Thread 'Sleeping' executing finally block.
//       Thread 'Sleeping finishing normal execution.
//
//       Thread 'Sleeping2' about to sleep indefinitely.
//       Thread 'Sleeping2' aborted.
//       Thread 'Sleeping2' executing finally block.
Imports System.Threading

Module Example
    Public Sub Main()
        ' Interrupt a sleeping thread. 
        Dim sleepingThread = New Thread(AddressOf Example.SleepIndefinitely)
        sleepingThread.Name = "Sleeping"
        sleepingThread.Start()
        Thread.Sleep(2000)
        sleepingThread.Interrupt()

        Thread.Sleep(1000)

        sleepingThread = New Thread(AddressOf Example.SleepIndefinitely)
        sleepingThread.Name = "Sleeping2"
        sleepingThread.Start()
        Thread.Sleep(2000)
        sleepingThread.Abort()
    End Sub

    Private Sub SleepIndefinitely()
        Console.WriteLine("Thread '{0}' about to sleep indefinitely.",
                          Thread.CurrentThread.Name)
        Try
            Thread.Sleep(Timeout.Infinite)
        Catch ex As ThreadInterruptedException
            Console.WriteLine("Thread '{0}' awoken.",
                              Thread.CurrentThread.Name)
        Catch ex As ThreadAbortException
            Console.WriteLine("Thread '{0}' aborted.",
                              Thread.CurrentThread.Name)
        Finally
            Console.WriteLine("Thread '{0}' executing finally block.",
                              Thread.CurrentThread.Name)
        End Try
        Console.WriteLine("Thread '{0} finishing normal execution.",
                          Thread.CurrentThread.Name)
        Console.WriteLine()
    End Sub
End Module
' The example displays the following output:
'       Thread 'Sleeping' about to sleep indefinitely.
'       Thread 'Sleeping' awoken.
'       Thread 'Sleeping' executing finally block.
'       Thread 'Sleeping finishing normal execution.
'       
'       Thread 'Sleeping2' about to sleep indefinitely.
'       Thread 'Sleeping2' aborted.
'       Thread 'Sleeping2' executing finally block.

Interruption de threadsInterrupting threads

Vous pouvez interrompre un thread en attente en appelant la méthode Thread.Interrupt sur le thread bloqué pour lever une ThreadInterruptedException, ce qui retirera le thread de l'appel bloquant.You can interrupt a waiting thread by calling the Thread.Interrupt method on the blocked thread to throw a ThreadInterruptedException, which breaks the thread out of the blocking call. Le thread doit intercepter la ThreadInterruptedException et faire tout le nécessaire pour continuer à fonctionner.The thread should catch the ThreadInterruptedException and do whatever is appropriate to continue working. Si le thread ignore l'exception, le runtime intercepte l'exception et arrête le thread.If the thread ignores the exception, the runtime catches the exception and stops the thread.

Notes

Si le thread cible n'est pas bloqué quand Thread.Interrupt est appelé, le thread ne sera pas interrompu avant d'être bloqué.If the target thread is not blocked when Thread.Interrupt is called, the thread is not interrupted until it blocks. Si le thread n'est jamais bloqué, il peut se terminer sans jamais être interrompu.If the thread never blocks, it could complete without ever being interrupted.

En cas d'attente managée, Thread.Interrupt et Thread.Abort réveillent le thread immédiatement.If a wait is a managed wait, then Thread.Interrupt and Thread.Abort both wake the thread immediately. En cas d'attente non managée (par exemple, dans le cas d'un appel de code non managé à la fonction Win32 WaitForSingleObject ), ni Thread.Interrupt ni Thread.Abort ne pourront prendre le contrôle du thread tant qu'il ne sera pas retourné dans du code managé ou tant qu'il n'effectuera pas d'appel depuis du code managé.If a wait is an unmanaged wait (for example, a platform invoke call to the Win32 WaitForSingleObject function), neither Thread.Interrupt nor Thread.Abort can take control of the thread until it returns to or calls into managed code. Dans du code managé, le comportement est le suivant :In managed code, the behavior is as follows:

Voir aussiSee also