How to kill a thread instantly in C#? How to kill a thread instantly in C#? multithreading multithreading

How to kill a thread instantly in C#?


The reason it's hard to just kill a thread is because the language designers want to avoid the following problem: your thread takes a lock, and then you kill it before it can release it. Now anyone who needs that lock will get stuck.

What you have to do is use some global variable to tell the thread to stop. You have to manually, in your thread code, check that global variable and return if you see it indicates you should stop.


You can kill instantly doing it in that way:

private Thread _myThread = new Thread(SomeThreadMethod);private void SomeThreadMethod(){   // do whatever you want}[SecurityPermissionAttribute(SecurityAction.Demand, ControlThread = true)]private void KillTheThread(){   _myThread.Abort();}

I always use it and works for me:)


You should first have some agreed method of ending the thread. For example a running_ valiable that the thread can check and comply with.

Your main thread code should be wrapped in an exception block that catches both ThreadInterruptException and ThreadAbortException that will cleanly tidy up the thread on exit.

In the case of ThreadInterruptException you can check the running_ variable to see if you should continue. In the case of the ThreadAbortException you should tidy up immediately and exit the thread procedure.

The code that tries to stop the thread should do the following:

running_ = false;threadInstance_.Interrupt();if(!threadInstance_.Join(2000)) { // or an agreed resonable time   threadInstance_.Abort();}