Killing a .NET thread
Solution 1:
Do not call Thread.Abort()
!
Thread.Abort
is dangerous. Instead you should cooperate with the thread so that it can be peacefully shut down. The thread needs to be designed so that it can be told to kill itself, for instance by having a boolean keepGoing
flag that you set to false when you want the thread to stop. The thread would then have something like
while (keepGoing)
{
/* Do work. */
}
If the thread may block in a Sleep
or Wait
then you can break it out of those functions by calling Thread.Interrupt()
. The thread should then be prepared to handle a ThreadInterruptedException
:
try
{
while (keepGoing)
{
/* Do work. */
}
}
catch (ThreadInterruptedException exception)
{
/* Clean up. */
}
Solution 2:
You should really only call Abort() as a last resort. You can use a variable to sync this thread instead:
volatile bool shutdown = false;
void RunThread()
{
while (!shutdown)
{
...
}
}
void StopThread()
{
shutdown = true;
}
This allows your thread to cleanly finish what it was doing, leaving your app in a known good state.