Should call EndRead () in all cases?

Regarding asynchronous I / O using the (bidirectional) NetworkStream MSDN, it says, "EndRead must be called once for every BeginRead call."

Is this true even when EndRead () throws an exception, for example, when NetworkStream was closed after BeginRead () exited?

I don't need the overhead of throwing an exception, but I also don't want the leak of valuable OS resources reserved by BeginRead ().

I also know that a thread can be closed between a thread state test and conditional EndRead (), but if EndRead () can be omitted, when we know that the thread is closed, this will save on exception handling in most cases.

Am I doing it wrong?

Thank!

+5
source share
1 answer

GCHandlethe binding of buffers and some other unmanaged resources is freed from the completion port callback. The unmanaged structure OVERLAPPEDwill hang until IAsyncResultit is completed. This may be acceptable if the network load in your application is small, but it can become a problem if your application processes a lot of connections per second, since finalization occurs only after a full GC collection and in a separate thread.

NB: these are implementation details obtained with Reflector. Caution emptor.

+4
source

All Articles