Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Must call EndRead() in ALL cases?

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!

like image 627
Jason Kleban Avatar asked Jun 17 '11 20:06

Jason Kleban


1 Answers

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.

like image 164
Anton Tykhyy Avatar answered Sep 19 '22 05:09

Anton Tykhyy