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.