How to terminate a thread in C#?
Asked Answered
F

4

19

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#?

Freedom answered 3/1, 2013 at 0:53 Comment(4)
It is usually best to let a thread "run out off the execution method itself" where it will indeed get terminated.Klement
Which version of .NET are you using?Exordium
Terminating threads is troublesome, but suicide is usually not. Like pthread_exit(). Thread.CurrentThread.Abort(). Not that useful.Tungusic
possible duplicate of Question about terminating a thread cleanly in .NETEames
T
81

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.

Terpsichore answered 3/1, 2013 at 1:7 Comment(4)
How you pass CancellationTokenSource to a System.Threading.Thread object?Exmoor
That dynamite analogy :P. +1Delegate
@Exmoor : Pass it as a parameter.Significs
Maybe some code would be helpful to improve this answer?Towrey
K
11

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.

Kibitz answered 3/1, 2013 at 0:58 Comment(4)
How would you terminate a socket listener thread that is listening to a port indefinitely? BTW, I believe Thread class does not accept CancellationToken, or does it?Exmoor
@Exmoor See the second referenced link in my answer, it gives you a CancellationToken example.Kibitz
Can you use CancellationToken with System.Threading.Thread class? Isn't it going to behave like an static boolean variable?Exmoor
@Exmoor Again, see the referenced thread "Cancellation of Managed Threads". It will behave however you write it to do so.Kibitz
T
4

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.

Thornton answered 3/1, 2013 at 0:57 Comment(3)
What you are suggesting is cool and acceptable, however, how you ask a Thread to "shut it already, now is my turn to talk"?Exmoor
Not sure what you specifically mean; but most people who write threaded code give the loops that run inside the thread an external signal that the thread's loop can check and shut down in an orderly way. If you have a specific scenario in mind, maybe you should post a question with the details.Thornton
You are absolutely correct. I do the same, however sometimes (e.g.) a listening socket gets stuck in a read loop and does not want to come out of loop and listen to your instruction to exit, in these cases, Thread.Abort() is the last resort to fix things up. You might loose some data but at least you saved your program from crashing.Exmoor
A
-2
Thread.Abort()
Thread.Join();
Thread = null;
Annatto answered 3/1, 2013 at 1:43 Comment(2)
Join does not terminate a thread, it waits until the thread is complete and is used if one needs to wait for completion of multiple threads (e.g. t1.Join(); t2.Join(); - typically the code that schedules/runs the threads uses this).Tiptop
Thread.Abort() is now deprecated and no longer works, and used to force kill the thread no matter what it does and what resources it still has open etc. The rest if this code does nothing to terminate a Thread.Cowherb

© 2022 - 2024 — McMap. All rights reserved.