using System; using System.Threading; class ThreadAbortApp { public static void WorkerThreadMethod() { try { Console.WriteLine("Worker thread started"); Console.WriteLine ("Worker thread - counting slowly to 10"); for (int i = 0; i < 10; i++) { Thread.Sleep(500); Console.Write("{0}...", i); } Console.WriteLine("Worker thread finished"); } catch(ThreadAbortException e) { } finally { Console.WriteLine ("Worker thread - I can't catch the exception, but I can cleanup"); } } public static void Main() { ThreadStart worker = new ThreadStart(WorkerThreadMethod); Console.WriteLine("Main - Creating worker thread"); Thread t = new Thread(worker); t.Start(); // Give the worker thread time to start. Console.WriteLine("Main - Sleeping for 2 seconds"); Thread.Sleep(2000); Console.WriteLine("\nMain - Aborting worker thread"); t.Abort(); } }
When you compile and execute this application, the following output results: -
Main - Creating worker thread Main - Sleeping for 2 seconds Worker thread started Worker thread - counting slowly to 10 0...1...2...3... Main - Aborting worker thread Worker thread - I can't catch the exception, but I can cleanup
You should also realize that when the Thread.Abort method is called, the thread will not cease execution immediately. The runtime waits until the thread has reached what the documentation describes as a "safe point." Therefore, if your code is dependent on something happening after the abort and you must be sure the thread has stopped, you can use the Thread.Join method. This is a synchronous call, meaning that it will not return until the thread has been stopped. Lastly, note that once you abort a thread, it cannot be restarted. In that case, although you have a valid Thread object, you can't do anything useful with it in terms of executing code.