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(); ... }
source share