Previously, the program used the thread. Abort () method to terminate the running of the thread, but it throws a threadabortexception exception to terminate the thread.
Exception summary:
Unhandled exception: thread was being aborted.
However, if you do not want to throw this exception and terminate the thread, the catch method is used to catch the exception. However, even after the exception is caught, the program will still report a threadabortexception exception.
Finally found a reasonable explanation in the http://msdn.microsoft.com/zh-cn/library/system.threading.threadabortexception.aspx.
Note:
When you call the abort method to destroy a thread, threadabortexception is triggered when the common language runs. Threadabortexception is a special exception that can be captured, but it will be automatically thrown again at the end of the Catch Block. When this exception is thrown, all finally blocks are executed before the pilot thread. Because the thread can run unbound computing in the Finally block or call thread. resetabort to cancel the suspension, it cannot be guaranteed that the thread will end completely. If you want to wait until the terminated thread ends, you can call the thread. Join method. Join is a blocking call, which is returned only when the thread actually stops running.
The handling method is to use thread. resetabort () to cancel the stop after the exception is caught to threadabortexception.
The following is a sample code on msdn:
1 using System; 2 using System.Threading; 3 using System.Security.Permissions; 4 5 public class ThreadWork { 6 public static void DoWork() { 7 try { 8 for(int i=0; i<100; i++) { 9 Console.WriteLine("Thread - working."); 10 Thread.Sleep(100);11 }12 }13 catch(ThreadAbortException e) {14 Console.WriteLine("Thread - caught ThreadAbortException - resetting.");15 Console.WriteLine("Exception message: {0}", e.Message);16 Thread.ResetAbort();17 }18 Console.WriteLine("Thread - still alive and working."); 19 Thread.Sleep(1000);20 Console.WriteLine("Thread - finished working.");21 }22 }23 24 class ThreadAbortTest {25 public static void Main() {26 ThreadStart myThreadDelegate = new ThreadStart(ThreadWork.DoWork);27 Thread myThread = new Thread(myThreadDelegate);28 myThread.Start();29 Thread.Sleep(100);30 Console.WriteLine("Main - aborting my thread.");31 myThread.Abort();32 myThread.Join();33 Console.WriteLine("Main ending."); 34 }35 }
View code
Execution result:
Thread - working. Main - aborting my thread. Thread - caught ThreadAbortException - resetting. Exception message: Thread was being aborted. Thread - still alive and working. Thread - finished working. Main ending.