.net TcpListener超时/关于/什么?没有异步?

.net TcpListener超时/关于/什么?没有异步?,.net,sockets,multithreading,tcplistener,.net,Sockets,Multithreading,Tcplistener,我创建了一个使用TcpListener的线程,当我的应用程序关闭时,我希望thead终止。我可以调用abort,但线程仍然处于活动状态,因为TcpListener正在使用AcceptTcpClient阻塞 是否可以使用AcceptTcpClient设置或设置超时或执行某些操作?如果没有办法阻止它永远阻塞,我无法想象它会有多大用处。我的代码是串行的,我希望它保持这种状态,那么有没有不使用BeginAcceptTcpClient的解决方案?是否编写异步代码?您可以将对AcceptTcpClient的

我创建了一个使用TcpListener的线程,当我的应用程序关闭时,我希望thead终止。我可以调用abort,但线程仍然处于活动状态,因为TcpListener正在使用AcceptTcpClient阻塞


是否可以使用AcceptTcpClient设置或设置超时或执行某些操作?如果没有办法阻止它永远阻塞,我无法想象它会有多大用处。我的代码是串行的,我希望它保持这种状态,那么有没有不使用BeginAcceptTcpClient的解决方案?是否编写异步代码?

您可以将对AcceptTcpClient的调用替换为对Socket.Select()的调用,该调用可能会超时

var sockl = new ArrayList { listener.Server };
Socket.Select(sockl, null, null, _timeout_);
if (sockl.Contains(listener.Server)) listener.AcceptTcpClient();

简单的解决方案。与待决客户进行核对

while(!server.Pending())
{
    Thread.Sleep(10);
}
TcpClient client = server.AcceptTcpClient();

我在(!Disposing)循环中使用
AcceptTcpClient()
来接受我的客户机。
当我处理类时,我调用
TcpListener
Stop()
函数,并将
Disposing
设置为true;像这样:

public class Server : IDisposable
{
    private TcpListener _tcpListener;
    private bool _isDisposing;

    public void Start()
    {
        (new Thread(new ThreadStart(ListenForClients))).Start();
    }

    private void ListenForClients()
    {
        this._tcpListener = new TcpListener(System.Net.IPAddress.Any, this.ListenPort);
        this._tcpListener.Start();

        while (!_isDisposing)
        {
            //blocks until a client has connected to the server
            TcpClient client = this._tcpListener.AcceptTcpClient();

            if (client == null) continue;

            //create a thread to handle communication with connected client
        }
    }

    public void Dispose()
    {
        this._isDisposing = true;
        this._tcpListener.Stop();
    }
}
请注意,这只是一个服务器类的小摘录

这样,程序就可以锁定在
AcceptTcpClient()
函数上,并且仍然可以结束。

但是,侦听本身也必须发生在一个单独的
线程(Start()函数)

上,这是阻止套接字代码永远不能投入生产的另一个原因。异步套接字通信是唯一100%可靠的方式。