AcceptTcpClient()
prevents app from exit after I called thrd.Abort()
.
How to exit application when in listening?
AcceptTcpClient()
prevents app from exit after I called thrd.Abort()
.
How to exit application when in listening?
您应该能够AcceptTcpClient()
通过关闭来中断对的调用TcpListener
(这将导致阻塞抛出异常AcceptTcpClient()
。您不应该中止线程,这通常是一个非常糟糕的主意,除了一些非常具体的情况。
这是一个简短的例子:
class Program
{
static void Main(string[] args)
{
var listener = new TcpListener(IPAddress.Any, 12343);
var thread = new Thread(() => AsyncAccept(listener));
thread.Start();
Console.WriteLine("Press enter to stop...");
Console.ReadLine();
Console.WriteLine("Stopping listener...");
listener.Stop();
thread.Join();
}
private static void AsyncAccept(TcpListener listener)
{
listener.Start();
Console.WriteLine("Started listener");
try
{
while (true)
{
using (var client = listener.AcceptTcpClient())
{
Console.WriteLine("Accepted client: {0}", client.Client.RemoteEndPoint);
}
}
}
catch(Exception e)
{
Console.WriteLine(e);
}
Console.WriteLine("Listener done");
}
}
上面的代码在单独的线程上启动了一个监听器,Enter在控制台窗口上按下会停止监听器,等待监听器线程完成,然后应用程序将正常退出,不需要线程中止!
你可以:
使用 BeginAcceptTcpClient() 和 End.. 代替:请参阅:https ://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener.beginaccepttcpclient(v=vs.110).aspx
或者你可以:
创建一个 TcpClient 并发送您的侦听器消息:
因此(我猜你的线程中有一个循环):
打破 listener.AcceptTcpClient() 正在运行的循环。(即 CancelAsync())从外部和 Loop While (!Tread.CancellationPending);
创建一个 TcpClient 并向您的侦听器发送一条消息(并丢弃数据);TcpClient 见:https ://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient(v=vs.110).aspx