Utilisation de la méthode ‘Thread.ResetAbort()’ pour annuler l’effet d’avortement d’un Thread

Author:


{filelink=17381}

using System;
using System.Threading; 

public class ExempleAbort2
{
  public static void Main()
  {
    MonThread thread1 = new MonThread("Thread #1");  

    // Suspendre le thread pendant une seconde
    Thread.Sleep(1000); 

    Console.WriteLine("Tentatif d'avortement de Thread.");
    thread1.objetThread.Abort(0); // Echec, car le code est 0

    // Suspendre le thread pendant une seconde
    Thread.Sleep(1000);

    Console.WriteLine("Tentatif d'avortement de Thread.");
    thread1.objetThread.Abort(100); // Tentatif reussi

     // Attendre la fin de Thread
    thread1.objetThread.Join();

    Console.WriteLine("Fin de Thread principal.");
  }
}
class MonThread
{
  public Thread objetThread;  

  public MonThread(string nom)
  {
    objetThread = new Thread(new ThreadStart(this.run));
    objetThread.Name = nom;
    objetThread.Start();
  }  

  void run()
  {
    Console.WriteLine(objetThread.Name + " Lancé."); 

    for(int i = 1000; i >0; i--) {
      try {
        Console.Write(i + " ");
        if((i%2)==0) {
          Console.WriteLine();
          Thread.Sleep(250);
        }
      } catch(ThreadAbortException err)
      {
          // Annuler l'Avortement si le code est 0
        if((int)err.ExceptionState == 0)
        {
          Console.WriteLine("Avortement du Thread Annulé! Code=" +
                             err.ExceptionState);
        // Méthode d'annulation
          Thread.ResetAbort();
        }
        else
          Console.WriteLine("Thread Avorté, code=" +
                             err.ExceptionState);
      }
    }
    Console.WriteLine(objetThread.Name + " Thread Terminé avec succès.");
  }
} 

Leave a Reply

Your email address will not be published. Required fields are marked *