How can I stop a thread in C#?

2019-02-20 02:32发布

问题:

I've created a Client-Server application, and on the Server I want to have the oportunity to stop the server and then start it again. The problem is that I can't stop the Thread that listen for Tcp Connections.

How can I close a Thread in C#?

Thanks.

private void KeepServer(){
    while (this.connected)
    {
         tcpClient = tls.AcceptTcpClient();
         Connection newConnection = new Connection(tcpClient);
    }
}

回答1:

In general, you should "stop" threads by indicating that you want them to stop, and letting them do it. It's recommended that you don't use Thread.Abort except for emergency situations where you're shutting down the whole application. (Calling Thread.Abort on the currently executing thread is safer, but still generally icky. That's what ASP.NET does when you redirect, by the way.)

I have a page about stopping threads gracefully. You don't have to use that exact code, of course - but the pattern of setting a flag and testing it periodically is the main point.

Now, how that gets applied in your particular situation will depend on how you're listening for TCP connections. If you could post the code used by that thread, we may be able to adapt it appropriately.



回答2:

Yor Question is a little general, but, I think that this may help you:

Threads in C#

I paste a portion:

Stopping a Thread

Normally, when a thread is started, it runs until finished. However, it is possible to stop a thread by calling the Abort() method. In our example, if we want to stop firstThread, you would add the following code.

Read more at Suite101: How to Create, Stop and Suspend Threads in C# | Suite101.com http://www.suite101.com/article.cfm/c_sharp/96436#ixzz0ZsZRRjKx

Happy coding!



回答3:

You should use a boolean or a condition to stop the Thread. You can than use a Property to change the "Flag" of this boolean and the loop of the Thread will end. This is a proper way to do it. Of course, you can use Abort() on the Thread but this is not recommended and will raise an Exception that you will need to handle.



回答4:

possible from the outside Thread.Abort and there is a way to pause. but its an incorrect way to do it...

you should just end the code to kill, reach the last } . and for pausing you should use a Mutex. the manner of opporation should be, you order the object to pause, and after it finishes with the current request it gets halt by the mutex before the next one. or just steps out side of the while for "kill".

btw the MSDN has a nice article describing common threading scenarios