.Net Meanderings

Richard Blewett's wanderings around .NET

Please read my disclaimer. Subscribe to my RSS feed

Thread.Abort still considered harmful

Back in the days of .NET 1.1 there was a nasty issue with Thread.Abort where the ThreadAbortException could be thrown out of a finally block this was one of the reasons you should not have called Thread.Abort in 1.1. For v2.0 this no longer happens, however, this can have its own issues. Consider the following code:

    class Program
    {
        static void Main(string[] args)
        {
            Thread t = new Thread(DoWork);

            t.IsBackground = true;
            t.Start();

            Thread.Sleep(500);
        }

        static void DoWork()
        {
            try
            {
            }
            finally
            {
                while (true)
                {
                    Console.Write(".");
                    Thread.Sleep(200);
                }
            }
        }
    }

This terminates quite happly as the thread is a back ground thread. Now lets change the code slightly:

    class Program
    {
        static void Main(string[] args)
        {
            Thread t = new Thread(DoWork);

            t.IsBackground = true;
            t.Start();

            Thread.Sleep(500);

            Console.WriteLine("aborting");
            t.Abort();
        }

        static void DoWork()
        {
            try
            {
            }
            finally
            {
                while (true)
                {
                    Console.Write(".");
                    Thread.Sleep(200);
                }
            }
        }
    }

All we've done here is abort the thread. However, because the Abort will not take place until the thread is out of the finally block, Abort does not return and so the program now doesn't terminate at all. So even though some of the problems with Thread.Abort have been fixed you still shouldn't call this API.

03/07/2006 2:35 PM | Comments [65] | #.NET

Content © 2003 Richard Blewett | Subscribe to my RSS feed.

Powered by BlogX