Do I need to call TcpListener.Stop()?
I have this code in a separate thread (Task) that runs first when the application starts and should not end until the application closes:
TcpListener tcpListener = new TcpListener(IPAddress.Any, port);
tcpListener.Start();
while (true)
{
TcpClient client = tcpListener.AcceptTcpClient();
Task.Factory.StartNew(HandleClientCommunication, client);
}
In this case is it necessary to call tcpListener.Stop()
? This thread runs for the entire duration of the application and if I did need to call it, where would I do so? The listener is local to this thread. Instead of having a while (true)
loop would I have a while (appRunning)
loop and set appRunning to false in the FormClosing event? Then after the while loop I could call tcpListener.Stop()
.
However, is it even necessary to call TcpListener.Stop()
because the application 开发者_如何学运维has already closed at that point and since I'm using Tasks the process ends as well?
Try something like that:
public class Listener
{
private readonly TcpListener m_Listener = new TcpListener(IPAddress.Any, IPEndPoint.MinPort);
private CancellationTokenSource m_Cts;
private Thread m_Thread;
private readonly object m_SyncObject = new object();
public void Start()
{
lock (m_SyncObject){
if (m_Thread == null || !m_Thread.IsAlive){
m_Cts = new CancellationTokenSource();
m_Thread = new Thread(() => Listen(m_Cts.Token))
{
IsBackground = true
};
m_Thread.Start();
}
}
}
public void Stop()
{
lock (m_SyncObject){
m_Cts.Cancel();
m_Listener.Stop();
}
}
private void Listen(CancellationToken token)
{
m_Listener.Start();
while (!token.IsCancellationRequested)
{
try{
var socket = m_Listener.AcceptSocket();
//do something with socket
}
catch (SocketException){
}
}
}
}
Approach with TcpListener.Pending()
is not so good because you must use Thread.Sleep(miliseconds)
or something like that - there will be some delay between clients accept(miliseconds in sleep), thats bad.
精彩评论