C#TcpListener.BeginAccept和ObjectDisposedException

时间:2016-01-06 00:32:38

标签: multithreading sockets c#-4.0 asynchronous network-programming

我在C#中遇到了丑陋的套接字管理模式,当我想要停止或关闭套接字时我必须捕获异常......

我想处理我的套接字,因此ObjectDisposedException不会弹出!

我想知道这段代码是否合适

private TcpListener server;
private bool listening;

private void Initialize() {

    this.listening = true;
    this.server = new TcpListener(ip, port);
    this.server.BeginAcceptTcpClient(this.AcceptSocket, null);
}

private void AcceptSocket(IAsyncResult result) {

    if (listening) this.server.EndAcceptTcpListener(result);
    else ; //Nothing or maybe some cleaning if necessary?
}

private void StopListening() {

    this.listening = false;
    this.server.Stop();
}

如您所知,Stop方法将触发AsyncCallback" AcceptSocket"底层套接字关闭,因此如果调用EndAcceptTcpListener,将抛出ObjectDisposedException ... 在这里,如果回调是由TcpListener.Stop触发的话,永远不会调用EndAcceptTcpListener!

所以,我想知道如果我不打电话给EndAcceptTcpListener会发生什么,因为msdn说我必须这样做,但我说如果我可以阻止它,我想要那个丑陋的异常!

如果它真的需要EndAccept我想知道你是否有一个解决方案来管理套接字停止并关闭谁避免那个愚蠢的异常!!

0 个答案:

没有答案