HI WELCOME TO Sirees

C# Threading Example: Abort() method

Leave a Comment
The Abort() method is used to terminate the thread. It raises ThreadAbortException if Abort operation is not done.
  1. using System;  
  2. using System.Threading;  
  3. public class MyThread  
  4. {  
  5.     public void Thread1()  
  6.     {  
  7.         for (int i = 0; i < 10; i++)  
  8.         {  
  9.             Console.WriteLine(i);  
  10.             Thread.Sleep(200);  
  11.         }  
  12.     }  
  13. }  
  14. public class ThreadExample  
  15. {  
  16.     public static void Main()  
  17.     {  
  18.         Console.WriteLine("Start of Main");  
  19.         MyThread mt = new MyThread();  
  20.         Thread t1 = new Thread(new ThreadStart(mt.Thread1));  
  21.         Thread t2 = new Thread(new ThreadStart(mt.Thread1));  
  22.   
  23.         t1.Start();  
  24.         t2.Start();  
  25.         try  
  26.         {  
  27.             t1.Abort();  
  28.             t2.Abort();  
  29.         }  
  30.         catch (ThreadAbortException tae)  
  31.         {  
  32.             Console.WriteLine(tae.ToString());  
  33.         }  
  34.         Console.WriteLine("End of Main");  
  35.     }  
  36. }  
Output:
Output is unpredictable because thread may be in running state.
Start of Main
0
End of Main

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.