我通过通常的异步回调从 UdpClient 接收数据:
private void OnUdpData(IAsyncResult result)
{
byte[] data = _udpReceive.EndReceive(result, ref _receiveEndPoint);
//Snip doing stuff with data
_udpReceive.BeginReceive(OnUdpData, null);
}
When I Close()
主线程中的 UdpClient,回调按我的预期触发,但此时_udpReceive
已被处置,我得到了ObjectDisposedException
当我尝试打电话时EndReceive()
。我期待得到一个空缓冲区。
处理这个问题的正确方法是什么?有没有成员UdpClient
我可以在尝试使用它之前进行检查,或者这是将其全部包装在一个中的唯一方法try{}
并抓住ObjectDisposedException
?对于正常的结束来说,这似乎非常令人讨厌。
您可以执行此操作来检查其是否已处理。当 UdpClient 被释放时,Client 被设置为 null。
private void OnUdpData(IAsyncResult result)
{
if (_udpReceive.Client == null)
return;
byte[] data = _udpReceive.EndReceive(result, ref _receiveEndPoint);
//Snip doing stuff with data
if (_udpReceive.Client == null)
return;
_udpReceive.BeginReceive(OnUdpData, null);
}
尽管因为您在单独的线程中关闭它,您可能最终会遇到竞争条件。最好只捕获 ObjectDisposeException 和 SocketException。
private void OnUdpData(IAsyncResult result)
{
try
{
byte[] data = _udpReceive.EndReceive(result, ref _receiveEndPoint);
//Snip doing stuff with data
_udpReceive.BeginReceive(OnUdpData, null);
}
catch (Exception e)
{
//You may also get a SocketException if you close it in a separate thread.
if (e is ObjectDisposedException || e is SocketException)
{
//Log it as a trace here
return;
}
//Wasn't an exception we were looking for so rethrow it.
throw;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)