在所有情况下都必须调用 EndRead() 吗?

发布于 2024-11-15 21:26:04 字数 449 浏览 1 评论 0原文

与使用(双向)NetworkStream 的异步 IO 相关,MSDN< /a> 表示“每次调用 BeginRead 时都必须调用一次 EndRead”。

即使对于 EndRead() 将抛出异常的情况(例如在发出 BeginRead() 后 NetworkStream 已关闭的情况)也是如此吗?

我不希望引发异常的开销,但我也不想泄漏 BeginRead() 保留的操作系统宝贵资源。

我还知道可以在流状态测试和条件 EndRead() 之间关闭流,但是如果当我们知道流已关闭时可以省略 EndRead(),则可以节省大多数情况下的异常处理。

我做错了吗?

谢谢!

Related to asynchronous IO using a (bidirectional) NetworkStream, MSDN says that "EndRead must be called once for every call to BeginRead."

Is this true even for cases where the EndRead() will throw an exception, such as in the case that the NetworkStream has been closed after the BeginRead() has been issued?

I don't want the overhead of the throwing of the exception, but neither do I want to leak OS precious resources reserved by BeginRead().

I also know that the stream could be closed between a test of the stream's state and the conditional EndRead(), but if EndRead() can be omitted when we know the stream is closed, that will save on the exception handling in the majority case.

Am I doing it wrong?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

白云不回头 2024-11-22 21:26:04

GCHandle 固定缓冲区和其他一些非托管资源由完成端口回调释放。非托管OVERLAPPED 结构将一直保留,直到IAsyncResult 完成。如果应用程序中的网络负载不大,这可能是可以忍受的,但如果应用程序每秒处理许多连接,这可能会成为问题,因为终结仅在完整 GC 收集之后并在单独的线程上发生。

注意:这些是通过 Reflector 获得的实现细节。买者自负。

GCHandles pinning your buffers and some other unmanaged resources are released by the completion port callback. The unmanaged OVERLAPPED structure will hang around until the IAsyncResult gets finalized. This may be tolerable if the network load in your application is not large, but may become a problem if your application handles many connections per second, because finalization happens only after a full GC collection and on a separate thread.

NB: these are implementation details, obtained with Reflector. Caveat emptor.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文