[Solved] How to terminate a thread in C#?

I wanted to try my luck in threading with C#, I know a few things about threading in C.

So I just wanted to ask if i wanted to terminate a thread, I should do it with smt.Abort()
or it will “kill itself” after the function ends?

Also, is there something like pthread_exit() in C in C#?

Solution #1:

Thread.Abort will “kill” the thread, but this is roughly equivalent to:

Scenario: You want to turn off your computer

Solution: You strap dynamite to your computer, light it, and run.

It’s FAR better to trigger an “exit condition”, either via CancellationTokenSource.Cancel, setting some (safely accessed) “is running” bool, etc., and calling Thread.Join. This is more like:

Scenario: You want to turn off your computer

Solution: You click start, shut down, and wait until the computer powers down.

Respondent: JerKimball
Solution #2:

You don’t need to terminate a thread manually once the function has ended.

If you spawn up a thread to run a method, once the method has returned the thread will be shut down automatically as it has nothing further to execute.*

You can of course, manually abort a thread by simply calling Abort(), but this is pretty much un-recommended due to potential thread state corruption due to unreliable determination of where a thread is at in its current execution state. If you need to handle the killing of threads yourself, you may be best looking into using a CancellationToken. You could also read up on the Cancellation of Managed Threads article on MSDN.

** That is, unless, you’re using a ThreadPool to perform your work. You shouldn’t worry about aborting these threads as they’re reused across different queued tasks.

Respondent: Rudi Visser
Solution #3:

Terminating a thread externally (from outside the thread) is a bad idea; you never know what the thread was in the middle of doing when you kill it asynchronously. In C#, if your thread function returns, the thread ends.

This MSDN article How to: Create and Terminate Threads (C# Programming Guide) has some notes and some sample code that you will probably find helpful.

Respondent: MikeB
Solution #4:
Thread = null;
Respondent: Dean
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.