i have a winform app that contains a form1 and the program.cs file. in program.cs i initialize form1 and besides that, i have a server included. My question is : how can i stop the threads when i close the form? here is part of my program.cs file :
public void start()
{
this.tcpListener = new TcpListener(IPAddress.Any, 3000);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();
}
private void ListenForClients()
{
//MessageBox.Show("in thread");
this.tcpListener.Start();
while (true)
{
//blocks until a client has connected to the server
TcpClient client = this.tcpListener.AcceptTcpClient();
//create a thread to handle communication
//with connected client
sThread a = new sThread(form1, listaThreads);
listaThreads.Add(a);
Thread clientThread = new Thread(new ParameterizedThreadStart(a.HandleClientComm));
clientThread.Start(client);
}
}
You can call
Close()of theTcpListenerfrom a different thread.TcpListener.Close()will simply callSocket.Close()and that is thread safe.I’m not sure how the
AcceptTcpClientreacts, but you’ll have to check that. At least it will stop your listening thread in a normal way.So, you do:
That will nicely close your thread.