我如何知道UdpClient是否已关闭/处置? [英] How do I know if UdpClient has been closed/disposed?

查看:346
本文介绍了我如何知道UdpClient是否已关闭/处置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过通常的异步回调从UdpClient接收数据:

I am receiving data from UdpClient via the usual async callback:

private void OnUdpData(IAsyncResult result)
{
    byte[] data = _udpReceive.EndReceive(result, ref _receiveEndPoint);

    //Snip doing stuff with data

    _udpReceive.BeginReceive(OnUdpData, null);
}

当我 Close()在主线程中的UdpClient中,回调将按我期望的方式触发,但是此时 _udpReceive 已被处置,并且我得到了 ObjectDisposedException 当我尝试调用 EndReceive()时。我本来只是希望得到一个空缓冲区。

When I Close() the UdpClient in the main thread, the callback fires as I would expect, but at this point _udpReceive is already disposed and I get an ObjectDisposedException when I try and call EndReceive(). I was expecting to just get an empty buffer.

处理此问题的正确方法是什么?我可以在使用 UdpClient 之前检查一下吗,还是将其全部包装在 try {}中的唯一方法并捕获 ObjectDisposedException

What is the correct way to handle this? Is there some member of UdpClient I can check before trying to use it, or it the only way to wrap it all in a try{} and catch the ObjectDisposedException? That seems pretty nasty for a normal close.

推荐答案

这完全是设计使然。您做了一些特殊的事情,即使您希望接收到数据,也还是关闭了套接字。因此,您将获得一个例外。 .NET框架始终可以确保异步调用已完成,并且在调用EndXxx()时在回调中指示了中止原因。一个好主意,那就是让您清理与回调相关的任何状态。

This is entirely by design. You did something exceptional, you closed the socket even though you expected data to be received. So you'll get an exception. The .NET framework always makes sure that asynchronous calls are completed and that the abort reason is signaled in the callback when you call EndXxx(). Good idea, that lets you clean up any state associated with the callback.

您可以将其设置为非异常,方法是等待传输完成,然后停止调用BeginReceive()然后然后关闭插槽。但这并不总是可行的,有时您真的想提前终止。没问题,只需捕获ObjectDisposedException并退出即可。当然,要做考虑线路另一端的应用程序会发生什么。它随后发送的任何内容都将落入位桶中,无法找到它。

You can make it non-exceptional by waiting until the transfer is complete, stop calling BeginReceive() and then close the socket. But that isn't always practical or sometimes you really want to terminate early. Not a problem, simply catch the ObjectDisposedException and get out. Of course, do consider what happens to the app on the other end of the wire. Anything it sends afterward is going to fall in the bit-bucket with no way for it to find out.

这篇关于我如何知道UdpClient是否已关闭/处置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆