我需要调用TcpListener.Stop()吗?
本文关键字:Stop TcpListener 调用 | 更新日期: 2023-09-27 18:09:07
我将这段代码放在一个单独的线程(Task)中,该线程在应用程序启动时首先运行,直到应用程序关闭时才应该结束:
TcpListener tcpListener = new TcpListener(IPAddress.Any, port);
tcpListener.Start();
while (true)
{
TcpClient client = tcpListener.AcceptTcpClient();
Task.Factory.StartNew(HandleClientCommunication, client);
}
在这种情况下,是否需要调用tcpListener.Stop()
?这个线程在整个应用程序期间运行,如果我确实需要调用它,我应该在哪里调用?侦听器是这个线程的本地侦听器。而不是有一个while (true)
循环,我会有一个while (appRunning)
循环,并设置appprunning为false在FormClosing事件?然后在while循环之后,我可以调用tcpListener.Stop()
。
然而,它甚至有必要调用TcpListener.Stop()
,因为应用程序已经关闭在那一点,因为我使用任务的进程结束了吗?
试试这样做:
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){
}
}
}
}
使用TcpListener.Pending()
的方法不是很好,因为你必须使用Thread.Sleep(miliseconds)
或类似的方法-在客户端接受之间会有一些延迟(睡眠中的毫秒),这很糟糕。