Proper server thread processing

I have a form for windows. The constructor server thread starts

thServer = new Thread(ServerThread); thServer.Start(); 

There is a TCP listener loop in the server thread:

  while (true) { TcpClient client = server.AcceptTcpClient(); ... } 

When I close the main form, this thread continues to wait for TCPClient requests. How can I stop this procedure? Thanks.

+1
source share
5 answers
 public partial class Form1 : Form { Thread theServer = null; public Form1() { InitializeComponent(); this.FormClosed += new FormClosedEventHandler( Form1_FormClosed ); theServer = new Thread( ServerThread ); theServer.IsBackground = true; theServer.Start(); } void ServerThread() { //TODO } private void Form1_FormClosed( object sender, FormClosedEventArgs e ) { theServer.Interrupt(); theServer.Join( TimeSpan.FromSeconds( 2 ) ); } } 
+1
source

The easiest way is to mark the stream as a background stream - then it will not support your process when closing the main form:

 thServer = new Thread(ServerThread); thServer.IsBackground = true; thServer.Start(); 

MSDN: Thread.IsBackground

+1
source

One approach is to add a flag that acts as a condition of the while loop. Of course, you can also set the IsBackground property of the Thread object, but you can execute some cleanup code.

Example:

 class Server : IDisposable { private bool running = false; private Thread thServer; public Server() { thServer = new Thread(ServerThread); thServer.Start(); } public void Dispose() { running = false; // other clean-up code } private ServerThread() { running = true; while (running) { // ... } } } 

Using:

 using (Server server = new Server()) { // ... } 
0
source

Here is a solution to the same problem. (look at the SimpleServer class)

The idea is to stop TcpClient , so the AcceptTcpClient call AcceptTcpClient interrupted. After calling AcceptTcpClient you may need to find out if the socket is open.

0
source

Make a special boolean variable indicating that the form is closing. Check its value in the background thread and break the loop when it is true. In the main form, set the variable to true and call thServer.Join () to wait for the stream to finish. Then you can safely close the form. Something like that:

In the form closing handler:

 abortThread = true; thServer.Join(); 

In the server thread chain:

 while (true) { if (abortThread) break; TcpClient client = server.AcceptTcpClient(); ... } 
0
source

Source: https://habr.com/ru/post/1432866/


All Articles