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!
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.