Terminating a Thread


It is sometimes useful to stop a thread prior to its normal conclusion. For example, a thread might be used to display the time of day. If the user does not desire a clock, its thread can be stopped. Once a thread has been terminated, it is removed from the system and cannot be restarted.

To terminate a thread, use Thread.Abort( ). Its simplest form is shown here:

 public void Abort( )

Abort( ) causes a ThreadAbortException to be thrown to the thread on which Abort( ) is called. This exception causes the thread to terminate. This exception can also be caught by your code (but is automatically rethrown in order to stop the thread). Abort( ) may not always be able to stop a thread immediately, so if it is important that a thread be stopped before your program continues, you will need to follow a call to Abort( ) with a call to Join( ). Also, in rare cases, it is possible that Abort( ) won’t be able to stop a thread. One way this could happen is if a finally block goes into an infinite loop.

The following example shows how to stop a thread:

 // Stopping a thread. using System; using System.Threading; class MyThread {   public Thread thrd;   public MyThread(string name) {     thrd = new Thread(this.run);     thrd.Name = name;     thrd.Start();   }   // This is the entry point for thread.   void run() {     Console.WriteLine(thrd.Name + " starting.");     for(int i = 1; i <= 1000; i++) {       Console.Write(i + " ");       if((i%10)==0) {         Console.WriteLine();         Thread.Sleep(250);       }     }     Console.WriteLine(thrd.Name + " exiting.");   } } class StopDemo {   public static void Main() {     MyThread mt1 = new MyThread("My Thread");     Thread.Sleep(1000); // let child thread start executing     Console.WriteLine("Stopping thread.");     mt1.thrd.Abort();     mt1.thrd.Join(); // wait for thread to terminate     Console.WriteLine("Main thread terminating.");   } }

The output from this program is shown here:

 My Thread starting. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 Stopping thread. Main thread terminating.

An Abort( ) Alternative

You might find a second form of Abort( ) useful in some cases. Its general form is shown here:

 public void Abort(object info)

Here, info contains any information that you want to pass to the thread when it is being stopped. This information is accessible through the ExceptionState property of ThreadAbortException. You might use this to pass a termination code to a thread. The following program demonstrates this form of Abort( ):

 // Using Abort(object). using System; using System.Threading; class MyThread {   public Thread thrd;   public MyThread(string name) {     thrd = new Thread(this.run);     thrd.Name = name;     thrd.Start();   }   // This is the entry point for thread.   void run() {     try {       Console.WriteLine(thrd.Name + " starting.");       for(int i = 1; i <= 1000; i++) {         Console.Write(i + " ");         if((i%10)==0) {           Console.WriteLine();           Thread.Sleep(250);         }       }       Console.WriteLine(thrd.Name + " exiting normally.");     } catch(ThreadAbortException exc) {       Console.WriteLine("Thread aborting, code is " +                          exc.ExceptionState);     }   } } class UseAltAbort {   public static void Main() {     MyThread mt1 = new MyThread("My Thread");     Thread.Sleep(1000); // let child thread start executing     Console.WriteLine("Stopping thread.");     mt1.thrd.Abort(100);     mt1.thrd.Join(); // wait for thread to terminate     Console.WriteLine("Main thread terminating.");   } }

The output is shown here:

 My Thread starting. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 Stopping thread. Thread aborting, code is 100 Main thread terminating.

As the output shows, the value 100 is passed to Abort( ). This value is then accessed through the ExceptionState property of the ThreadAbortException caught by the thread when it is terminated.

Canceling Abort( )

A thread can override a request to abort. To do so, the thread must catch the ThreadAbortException and then call ResetAbort( ). This prevents the exception from being automatically rethrown when the thread’s exception handler ends. ResetAbort( ) is declared like this:

 public static void ResetAbort( )

A call to ResetAbort( ) can fail if the thread does not have the proper security setting to cancel the abort.

The following program demonstrates ResetAbort( ):

 // Using ResetAbort(). using System; using System.Threading; class MyThread {   public Thread thrd;   public MyThread(string name) {     thrd = new Thread(this.run);     thrd.Name = name;     thrd.Start();   }   // This is the entry point for thread.   void run() {     Console.WriteLine(thrd.Name + " starting.");     for(int i = 1; i <= 1000; i++) {       try {         Console.Write(i + " ");         if((i%10)==0) {           Console.WriteLine();           Thread.Sleep(250);         }       } catch(ThreadAbortException exc) {         if((int)exc.ExceptionState == 0) {           Console.WriteLine("Abort Cancelled! Code is " +                              exc.ExceptionState);           Thread.ResetAbort();         }         else           Console.WriteLine("Thread aborting, code is " +                              exc.ExceptionState);       }     }     Console.WriteLine(thrd.Name + " exiting normally.");   } } class ResetAbort {   public static void Main() {     MyThread mt1 = new MyThread("My Thread");     Thread.Sleep(1000); // let child thread start executing     Console.WriteLine("Stopping thread.");     mt1.thrd.Abort(0); // this won't stop the thread     Thread.Sleep(1000); // let child execute a bit longer     Console.WriteLine("Stopping thread.");     mt1.thrd.Abort(100); // this will stop the thread     mt1.thrd.Join(); // wait for thread to terminate     Console.WriteLine("Main thread terminating.");   } }

The output is shown here:

 My Thread starting. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 Stopping thread. Abort Cancelled! Code is 0 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 Stopping thread. Thread aborting, code is 100 Main thread terminating.

In this example, if Abort( ) is called with an argument that equals zero, then the abort request is canceled by the thread by calling ResetAbort( ), and the thread’s execution continues. Any other value causes the thread to stop.




C# 2.0(c) The Complete Reference
C# 2.0: The Complete Reference (Complete Reference Series)
ISBN: 0072262095
EAN: 2147483647
Year: 2006
Pages: 300

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net