Avorter un Thread avec la méthode ‘Abort()+’

Author:


{filelink=17380}

using System;
using System.Threading; 

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

    Thread.Sleep(1000); // Suspendre le thread

    Console.WriteLine("Provoquer l'avortement du Thread. avec un code d'erreur");
    monThread.objetThread.Abort(100);

    monThread.objetThread.Join(); 

  }
}

class MonThread
{
  public Thread objetThread;  

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

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

      for(int i = 1000; i >= 0; i--)
      {
        Console.Write(i + " ");
        if((i%2)==0) {
          Console.WriteLine();
          Thread.Sleep(500);
        }
      }
      Console.WriteLine(objetThread.Name + " Terminé avec succès.");
    } catch(ThreadAbortException err)
    {
      Console.WriteLine("Thread Avorté, erreur: " +
                         err.ExceptionState);
    }
  }
} 

Leave a Reply

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