How to terminate a thread in C#?

前端 未结 4 1613
無奈伤痛
無奈伤痛 2020-11-27 20:38

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

相关标签:
4条回答
  • 2020-11-27 20:41
    Thread.Abort()
    Thread.Join();
    Thread = null;
    
    0 讨论(0)
  • 2020-11-27 20:48

    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.

    0 讨论(0)
  • 2020-11-27 20:50

    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.

    0 讨论(0)
  • 2020-11-27 21:00

    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.

    0 讨论(0)
提交回复
热议问题