What is a safe way to stop a running thread?

aplavin picture aplavin · Feb 14, 2012 · Viewed 31.5k times · Source

I have a thread which contains execution of an IronPython script. For some reason I may need to stop this thread at any time, including script execution. How to achieve this? The first idea is Thread.Abort(), but it's known to be evil...

Answer

Eric Lippert picture Eric Lippert · Feb 14, 2012

What is a safe way to stop a running thread?

Put the thread in its own process. When you want it to stop, kill the process.

That is the only safe way to kill a thread. Aborting a thread can severely destabilize a process and lose user data. There's no way to avoid the "lose user data" scenario if you really, truly need to be able to kill a thread that could be doing anything. The only way to avoid destabilizing the process that is calling for the abort is to make them different processes entirely.