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?
-
48Did you read the "remark" section on the MSDN? NEVER USE ABORT. IT IS INTENDED AS LAST RESORT. IF YOU USE THREAD.ABORT, SKY MAY FALL DOWN, AND KITTEN WILL BE KILLED. – J-16 SDiZ Jun 27 '09 at 02:27
-
1Kitten? I thought it was the chicken :) But your profile pic explains your comment! – Rashmi Pandit Jun 27 '09 at 10:10
-
4As others have said, do your best to never do this; you should try to never create a thread that does something that you cannot control. If you have to kill running code that you cannot control, the safest thing to do is to run the code in another PROCESS, not another THREAD. It is a lot safer to take down a process than a thread. – Eric Lippert Jun 27 '09 at 16:34
8 Answers
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. */
}

- 349,597
- 67
- 533
- 578
-
6Using exception handling to control program flow is a horrible idea. Use a WaitHandle instead. – Mark Seemann Jun 27 '09 at 06:11
-
6I don't think it's that horrible. If your loop is not tight enough and it might take 30 seconds of processing before it finally knows that it should exit, an exception is the perfect way to stop it. – Jimbo Apr 29 '10 at 17:59
-
6Mark, what if your thread is blocking for input and you need to make it stop somehow? It can block indefinitely, so Interrupting it and handling the exception is about the only way you can make it exit. – Kiril Sep 03 '10 at 00:10
-
1@Lirik Then you should be using the non-blocking versions, or cancel-able async calls. Think `select()` in Unix. – Jonathon Reinhart Nov 12 '13 at 06:32
-
So how do you get the thread out of SqlCommand.ExecuteNonQuery()? Dont' say call Async() here you just moved the problem. – Joshua Jul 17 '21 at 19:45
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.

- 51,025
- 31
- 133
- 161
The most correct and thread-safe way is to use a WaitHandle to signal to the thread when it's supposed to stop. I mostly use ManualResetEvent.
In your thread, you can have:
private void RunThread()
{
while(!this.flag.WaitOne(TimeSpan.FromMilliseconds(100)))
{
// ...
}
}
where this.flag
is an instance of ManualResetEvent. This means that you can call this.flag.Set()
from outside the thread to stop the loop.
The WaitOne method will only return true when the flag is set. Otherwise, it will time out after the specified timeout (100 ms in the example) and the thread will run through the loop once more.

- 225,310
- 48
- 427
- 736
-
1The downside of your implementation is that on each loop you gonna wait for the event, doing nothing. I'd rather to the contrary. Having a flag that indicate to shutdown and signal that the tread have end the execution. `while (!WillTerminate) {..} HasTerminate.Set();` – mathk Jul 30 '12 at 10:15
-
It is not a good idea to kill a thread. It is better to signal that it should stop and let it end gracefully. There are various different ways of doing this.
- Use
Thread.Interrupt
to poke it if it is blocked. - Poll a flag variable.
- Use the
WaitHandle
class to send a signal.
There is no need for me to rehash how each method can be used since I have already done so in this answer.

- 1
- 1

- 47,849
- 13
- 107
- 150
-
2+1. can you supply a simple example killing/stopping a thread via wait handle ? – Royi Namir Jul 23 '12 at 07:47
Aborting a thread is a very bad idea, since you cannot determine what the thread was doing at the time of the abort.
Instead, have a property that the thread can check, and that your external code can set. Let the thread check this boolean property when it's at a safe place to exit.

- 160,644
- 26
- 247
- 397
I agree to Jon B
volatile bool shutdown = false;
void RunThread()
{
try
{
while (!shutdown)
{
/* Do work. */
}
}
catch (ThreadAbortException exception)
{
/* Clean up. */
}
}
void StopThread()
{
shutdown = true;
}

- 153,850
- 22
- 249
- 325

- 161
- 3
- 16
There are also examples of killing threads in my WebServer class...
https://net7ntcip.codeplex.com/SourceControl/changeset/view/89621#1752948
I would say Abort is okay just understand what the ramifications are... as long as you are indicating state before a long running task Abort will work but flags are required such as (ShouldStop or ActionBranch etc)
Check it out for examples!

- 3,276
- 1
- 28
- 38
Edit:
I created a little class for this
Noticed it didn't work with async/await
Posted an update to the class, then Theodor Zoulias (thanks :)) let me know this idea was flawed.
Now I'm reposting the original class (doesn't work with async/await!)
var t = new StopAbleThread(isShutDown => { Console.WriteLine("a"); while (!isShutDown()) { Console.WriteLine("b"); Thread.Sleep(TimeSpan.FromMinutes(10)); } } ) { IsBackground = true }; t.Start( );
Stop the thread like this:
t.Stop();
The class:
public class StopAbleThread
{
public bool IsBackground
{
set => _thread.IsBackground = value;
}
private readonly Thread _thread;
private volatile bool _shutdown;
public delegate bool IsShutDown( );
public delegate void CodeToRun( IsShutDown isShutDown );
public StopAbleThread( CodeToRun codeToRun )
{
_thread = new Thread( ( ) =>
{
try
{
codeToRun( _IsShutDown );
}
catch( ThreadInterruptedException )
{
//ignore
}
} );
}
private bool _IsShutDown( )
{
return _shutdown;
}
public void Start( )
{
_thread.Start( );
}
public void Stop( )
{
_shutdown = true;
_thread.Interrupt( );
}
}

- 25
- 1
- 6
-
The `Thread` constructor does not understand async delegates. You can read about this [here](https://stackoverflow.com/questions/44364092/is-it-ok-to-use-async-with-a-threadstart-method) or [here](https://stackoverflow.com/questions/30044846/async-thread-body-loop-it-just-works-but-how). As a result the `_thread.Interrupt()` is going to interrupt an already terminated thread, so it won't do anything in practice. – Theodor Zoulias Jul 16 '21 at 16:02
-
Thanks for the comment. The code above is working as expected for my use case. The interrupt call does wake the thread when sleeping. – Rowi123 Jul 16 '21 at 20:16
-
The [first revison](https://stackoverflow.com/revisions/68406819/1) of your answer was OK, because all code was synchronous. By adding async/await you created a flawed version that is not going to work consistently. There is no guarantee that the code after an `await` point will continue running on the same thread as before the await. In your example the `await Task.Delay(1)` point is where the `_thread` is going to terminate, and the subsequent `Thread.Sleep(FromMinutes(10))` will put to sleep a `ThreadPool` thread instead of the `_thread`. And then the `_thread.Interrupt();` will do nothing. – Theodor Zoulias Jul 17 '21 at 00:06
-
If you don't believe me, log to the `Console` the `Thread.CurrentThread.ManagedThreadId` before and after the `await`, and see whether it's the same or not. – Theodor Zoulias Jul 17 '21 at 00:15
-
Okay, thanks again. Think i should repost the first solution? And i really need a solution with await. Do you know a better way? – Rowi123 Jul 17 '21 at 09:05
-
Yeap, I would suggest to [rollback](https://stackoverflow.com/posts/68406819/revisions) to the revision 1. As for how to terminate non-cooperatively an asynchronous operation, I honestly don't know! – Theodor Zoulias Jul 17 '21 at 10:07