在所有情况下都必须调用 EndRead() 吗?
与使用(双向)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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
GCHandle 固定缓冲区和其他一些非托管资源由完成端口回调释放。非托管
OVERLAPPED
结构将一直保留,直到IAsyncResult
完成。如果应用程序中的网络负载不大,这可能是可以忍受的,但如果应用程序每秒处理许多连接,这可能会成为问题,因为终结仅在完整 GC 收集之后并在单独的线程上发生。注意:这些是通过 Reflector 获得的实现细节。买者自负。
GCHandle
s pinning your buffers and some other unmanaged resources are released by the completion port callback. The unmanagedOVERLAPPED
structure will hang around until theIAsyncResult
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.