May 9, 2008

Thread Interrupt vs Abort

Both methods can terminate a thread. The difference is that they raise difference exception, interrupt can use goto to save its life, abort can not use goto to save its life, and abort can pass some information into the running thread by calling Abort(object stateInfo). The running thread can access this object by ThreadAbortException.ExceptionState .

            class Program
            {
            static void Main(string[] args)
            {
            ThreadStart ts = new ThreadStart(DoSomething);
            Thread t = new Thread(ts);
            t.Start();
            Thread.Sleep(1000);
            //t.Interrupt();
            t.Abort();
            Console.WriteLine("mainthread finished");
            }

            static void DoSomething()
            {
            Resurrection:
            try
            {
            Thread.Sleep(2000);
            Console.WriteLine("do something finished");
            }
            catch (ThreadInterruptedException ex)
            {
            Console.WriteLine("DoSomething is interrupted");
            goto Resurrection;

            }
            catch (ThreadAbortException ex)
            {
            Console.WriteLine("DoSomething is aborted");
            goto Resurrection;
            }

            }

            }