如上所述,.EndConnect()代码行返回ObjectDisposedException。
为什么呢? 这是代码:
private TCPResult ConnectToHost(string hostname, int port) {
IPAddress cachedDNS = DirectDNS.GetDNS(ref MainForm.DNS, hostname);
TcpClient tcp = new TcpClient();
try {
#region Try connect
IAsyncResult ar = tcp.BeginConnect(cachedDNS, port, (ari) => {
TcpClient tcpi = (TcpClient)ari.AsyncState;
try {
tcpi.EndConnect(ari);
} catch { }
if (tcpi.Connected) {
return; //return IAsyncResult and waitone will be true
}
tcpi.Close();
}, tcp);
#endregion
#region If timed out, or not connected return null
if(!ar.AsyncWaitHandle.WaitOne(_connectTimeout, false)) {
return new TCPResult() {
Result = null,
Error = HttpError.ConnectToHostTimeout
};
}
if (!tcp.Connected) {
return new TCPResult() {
Result = null,
Error = HttpError.GeneralNotConnected
};
}
#endregion
} catch (Exception ex) {
return new TCPResult() {
Result = null,
Error = HttpError.ConnectToHostException,
Information = ex.GetType().Name + " - " + ex.Message
};
}
tcp.SendTimeout = _readWriteTimeout;
tcp.ReceiveTimeout = _readWriteTimeout;
return new TCPResult() {
Result = tcp,
Error = HttpError.Success
};
}
是什么原因导致ObjectDisposed异常,因为这里没有什么对我真正突出。
通过查看调用堆栈,我可以看到此异常是由.EndConnect对Client.EndConnect的内部调用(其中Client = Socket Object)引发的,然后由THAT的内部EndConnect调用引发的