Killing a .NET thread

Jorge Branco picture Jorge Branco · Jun 27, 2009 · Viewed 67.4k times · Source

I have created a thread running a certain method. But sometimes I would like to kill the thread even if it is still working. How can I do this? I tried Thread.Abort() but it shows up a messagebox saying "Thread aborted". What should I do?

Answer

John Kugelman picture John Kugelman · Jun 27, 2009

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. */
}