Reputation: 11137
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);
}
}
Upvotes: 1
Views: 1551
Reputation: 838096
Rather than actively aborting them you should signal to them that they should stop and allow them to stop in their own time. If you are using any BackgroundWorker
s you can use the CancelAsync
method. For the threads created manually like in your example you can use a boolean flag (with appropriate synchronization) that the thread must occasionally check. When your program is about to close set the flag. Avoid calling blocking methods in your threads - use the asynchronous methods instead such as BeginAcceptTcpClient
instead of AcceptTcpClient
.
If you are using (or can upgrade to) .NET 4 then you should also consider using the Task Parallel Library where tasks are cancellable.
Upvotes: 3
Reputation: 29632
You can call Close()
of the TcpListener
from a different thread.
TcpListener.Close()
will simply call Socket.Close()
and that is thread safe.
I'm not sure how the AcceptTcpClient
reacts, but you'll have to check that. At least it will stop your listening thread in a normal way.
So, you do:
tcpListener.Close();
listenThread.Join();
That will nicely close your thread.
Upvotes: 3
Reputation: 6617
In the method that runs async you should check for a boolean flag say cancel
that you set to true from outside when you want to stop the thread.
public bool cancel = false;
public void MethodRuningOnThread()
{
while(!cancel)
{
//do stuff
}
}
It is not recommended to use the Thread.Abort()
method.
Upvotes: 0