Meir Tolpin Meir Tolpin - 2 months ago 9
C# Question

Kill multi threading Server's thread c#

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


here it the server code:

private void start()
{
try
{
this.serverSocket = new TcpListener(8888); // creating the Server TCP socket
this.clientSocket = default(TcpClient); // creating the User socket variable

// starting the server
this.serverSocket.Start();

Console.WriteLine("->> server started"); // printing to log

// for always
while (true)
{
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);
user.startListerner();
}

this.clientSocket.Close();
this.serverSocket.Stop();
Console.WriteLine(" >> " + "exit");
Console.ReadLine();
}
catch
{
Console.WriteLine("Error launching the Server");
}

}


and I run it this way:

this.server = new Thread(start);
server.Start();


I want to terminate it , how can I do that ?

Answer

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.

Comments