如何中止使用AcceptTcpClient()的线程?

Hal*_*lla 4 c#

AcceptTcpClient()我打电话后阻止app退出thrd.Abort().

如何在聆听时退出应用程序?

Iri*_*ium 8

您应该能够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");
    }
}
Run Code Online (Sandbox Code Playgroud)

上面的代码在一个单独的线程上启动一个监听器,按下Enter控制台窗口将停止监听器,等待监听器线程完成,然后应用程序将正常退出,不需要线程中止!