I have a program that starts a server thread, in that thread I wait for user connections, but sometimes (if the user presses "E") I want to close that server thread but it's not working. I tried
'thread'.abort() - but it's freezing and not stopping the thread
private void start()
this.serverSocket = new TcpListener(8888); // creating the Server TCP socket
this.clientSocket = default(TcpClient); // creating the User socket variable
// starting the server
Console.WriteLine("->> server started"); // printing to log
// for always
counter += 1; // new user
this.clientSocket = this.serverSocket.AcceptTcpClient(); // accepting user
Console.WriteLine(" ->> User connected"); // printing to log
// User creatinon
ConnectedUser user = new ConnectedUser(this.clientSocket);
Console.WriteLine(" >> " + "exit");
Console.WriteLine("Error launching the Server");
this.server = new Thread(start);
You'll have to use a
CancellationTokenSource to signal your thread to terminate itself. Using
Thread.Abort is not recommended because it terminates the thread without letting it properly clean up first.
To use the cancellation token, you create an instance of
CancellationTokenSource and then pass the token to your thread function (or to an object that wraps the new thread state. Inside the thread function you can then check the
IsCancellationRequested property of the token periodically to see if the thread should shut down. You can pass the same cancellation token to I/O functions so they attempt to cancel a blocking operation.
Read this question/ answers for more detail about the possible issues caused by
Thread.Abort. Specifically read Eric Lippert's response to that question where he mentions never to start a thread that you cannot politely stop.