在 TcpClient 实例上读取 Connected 属性 时出现异常
Getting exception while reading Connected property on TcpClient instance
public bool IsConnected
{
get { return _tcpClient == null ? false : _tcpClient.Connected; }
}
抛出
"Object reference not set to an instance of an object."
在
at System.Net.Sockets.TcpClient.get_Connected()
at Project.ViewModel.ModbusOutputCounter.get_IsConnected() in C:...\ModbusOutputCounter.cs:line 115
这怎么可能,我们怎样才能避免接收到这个异常?
编辑:
根据 svk 的回答,问题出在 Disposing 中,它在 Close() 方法中内部调用。解决方法:
return _tcpClient?.Client != null ? _tcpClient.Connected : false;
根据reference source for TcpClient
,Connected
直接returns Connected
底层套接字。这意味着当套接字为 null
时 Connected
将抛出 NullReferenceException
。通过浏览参考资料,我发现了两种可能发生的情况:
- 当
TcpClient
已经 Dispose
d.
- 当您将
Client
Socket
显式设置为 null
时。
public bool IsConnected
{
get { return _tcpClient == null ? false : _tcpClient.Connected; }
}
抛出
"Object reference not set to an instance of an object."
在
at System.Net.Sockets.TcpClient.get_Connected() at Project.ViewModel.ModbusOutputCounter.get_IsConnected() in C:...\ModbusOutputCounter.cs:line 115
这怎么可能,我们怎样才能避免接收到这个异常?
编辑:
根据 svk 的回答,问题出在 Disposing 中,它在 Close() 方法中内部调用。解决方法:
return _tcpClient?.Client != null ? _tcpClient.Connected : false;
根据reference source for TcpClient
,Connected
直接returns Connected
底层套接字。这意味着当套接字为 null
时 Connected
将抛出 NullReferenceException
。通过浏览参考资料,我发现了两种可能发生的情况:
- 当
TcpClient
已经Dispose
d. - 当您将
Client
Socket
显式设置为null
时。