我正在尝试使用
场景如下:
基本上,我不知道发生了什么。问题在于我被迫等待应用程序关闭(好像连接操作仍在等待超时)。如果服务器在线,它就可以正常连接和断开连接。
在这种情况下,NullReferenceException是什么意思?如何避免
TcpClient.BeginConnect / TcpClient.EndConnect
组合连接到我的服务器。然而,有些事情并不像它们应该的那样工作。场景如下:
- 调用
TcpClient.BeginConnect
- 服务器故意离线(用于测试目的) - 因此无法建立连接。
- 我关闭应用程序(在过程中调用了
client.Close()
,这将关闭套接字,从而停止异步操作) TcpClient
连接回调方法发生,给出了IAsyncResult
- 使用给定的
IAsyncResult
调用TcpClient.EndConnect
方法 EndConnect
上发生NullReferenceException
(?)- 由于最后一个窗体(窗口)已关闭,因此应用程序应退出 - 但它没有,至少在
BeginConnect
操作完成之前不会退出(这很奇怪,因为回调已经被调用)。
NullReferenceException
异常。从上面的图片中可以看出,client
和ar
都不是null
。问题在于MSDN EndConnect文档没有提到抛出此异常的情况。基本上,我不知道发生了什么。问题在于我被迫等待应用程序关闭(好像连接操作仍在等待超时)。如果服务器在线,它就可以正常连接和断开连接。
在这种情况下,NullReferenceException是什么意思?如何避免
BeginConnect
操作在连接无法建立的情况下阻止应用程序关闭?
附加说明(在评论中请求):
以下是创建客户端的代码(客户端是一个成员变量):
public void Connect()
{
try
{
lock (connectionAccess)
{
if (State.IsConnectable())
{
// Create a client
client = new TcpClient();
client.LingerState = new LingerOption(false, 0);
client.NoDelay = true;
State = CommunicationState.Connecting;
client.BeginConnect(address, port, onTcpClientConnectionEstablished, null);
}
else
{
// Ignore connecting request if a connection is in a state that is not connectable
}
}
}
catch
{
Close(true);
}
}
还有 Close 方法:
public void Close(bool causedByError)
{
lock (connectionAccess)
{
// Close the stream
if (clientStream != null)
clientStream.Close();
// Close the gateway
if (client != null)
client.Close();
// Empty the mailboxes
incomingMailbox.Clear();
outgoingMailbox.Clear();
State = causedByError ? CommunicationState.CommunicationError : CommunicationState.Disconnected;
}
}