开发者

Handle leak when socket is forcibly closed by remote host? (.net)

开发者 https://www.devze.com 2022-12-21 00:21 出处:网络
I have created a simple tcp based \"echo protocol\" and notice that I suffer from handle leak on 开发者_如何学Cthe server when the client forcibly closes the connection (sends a reset).

I have created a simple tcp based "echo protocol" and notice that I suffer from handle leak on 开发者_如何学Cthe server when the client forcibly closes the connection (sends a reset).

I catch the ConnectionReset and dispose the socket in the same way I do when the socket is closed (socket.Shutdown and socket.close). As anybody encountered such a problem? The ConnectionReset exception is thrown while I'm doing a socket.Read, if it matters.

Thanks.

Edit: Microsoft's DebugDiag tool suggests those are event handlers created by MSCORLIB. Needless to say that I don't create those directly (but they are created somewhere by the .net library)


Socket.Recieve and Socket.Write are, unfortunately, the only places to detect when the other end closes it's sockets forcibly rather than correctly.

Socket.Close() should (according to my intellisense) release the socket handle.

So first make sure Socket.Close() is indeed being called. Then check other places for handle leaks, are you using any objects that require disposing that aren't being disposed? Such as opening FileStreams?


I think you do it right:

Socket.Close should free all managed and unmanaged ressources associated to the socket.

But did you also try to set

socket = null;

And maybe (after that) use

GC.Collect();

to manually trigger the garbage collector, is the leak still present after this?

Another idea: How do you monitor the handle leak? The OS might keep a closed TCP connection in memory for a long time (minutes), this is normal behaviour.

0

精彩评论

暂无评论...
验证码 换一张
取 消