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 wi
Thread.Abort()
Thread.Join();
Thread = null;
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.
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.
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.