Thread.Abort() + finally == scary
Saw an interesting post on the DOTNET-LANGUAGE-DEVS list today that mentioned "interesting" behavior with Thread.Abort(). Calling this function raises an exception in the thread object, which the thread normally can handle prior to shutting down. Nice and clean. Joe Marshal pointed out a somewhat nasty little race condition, however - if the call to Abort comes out while the thread is executing a finally block the finally block is abandoned (!). I whipped up this little bit of code to test it out. Moral of the story - be very careful with Thread.Abort().
using System; using System.Threading;
class Nasty { static void ThreadProc() { try { try { Console.WriteLine("executing try block"); } finally { Console.WriteLine("Starting Finally block");
Thread.Sleep(5000);
//This line of code will never execute. If someone //aborts the thread *while we're in the finally block* //the execution of the finally block will be abandoned. Console.WriteLine("Done with finally block"); } } catch(Exception e) { Console.WriteLine("Exception caught! {0}", e.GetType()); } }
static void Main() { Thread th = new Thread(new ThreadStart(ThreadProc)); th.Start();
//These two lines of code crudely guarantee that we //will abort the thread while it's in the middle of its //finally block. Thread.Sleep(1000); th.Abort();
Console.WriteLine("press a key to exit"); Console.ReadLine(); } }
9:23:44 AM
|