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);
}
}
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.Abortexcept for emergency situations where you’re shutting down the whole application. (CallingThread.Aborton 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.