C Sharp

Destroying Threads

If the need should arise to destroy a thread, you can accomplish this with a call to the Thread.Abort method. The runtime forces the abortion of a thread by throwing a ThreadAbortException. Even if the method attempts to catch the ThreadAbortException, the runtime won't let it. However, the runtime will execute the code in the aborted thread's finally block, if one's present. The following code illustrates what I mean. The Main method pauses for two seconds to make sure that the runtime has had time to start the worker thread. Upon being started, the worker thread starts counting to ten, pausing for a second in between each number. When the Main method resumes execution after its two-second pause, it aborts the worker thread. Notice that the finally block is executed after the abort.

using System;
using System.Threading;
class ThreadAbortApp
    public static void WorkerThreadMethod()
            Console.WriteLine("Worker thread started");
                ("Worker thread - counting slowly to 10");
            for (int i = 0; i < 10; i++)
                Console.Write("{0}...", i);
            Console.WriteLine("Worker thread finished");
        catch(ThreadAbortException e)
                ("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);
        // Give the worker thread time to start.
        Console.WriteLine("Main - Sleeping for 2 seconds");
        Console.WriteLine("\nMain - Aborting worker thread");

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
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.

by BrainBellupdated