How to detect a handle leak with a GC

  • Thread starter Thread starter joproulx
  • Start date Start date
J

joproulx

After trying to investigate a handle leak problem in my application, I
found out this post which pretty much describes the behavior that I
have experienced:
http://www.dotnet247.com/247reference/msgs/51/255221.aspx

And here is part of my code:

private void Socket_AcceptConnectCallback(IAsyncResult ar)
{
Socket socket = (Socket)ar.AsyncState;

if( socket==null )
return;

if ( socket.Connected)
{
socket.EndConnect(ar);
// Connection succeeded
CreateNewConnection(socket, out
m_iClientMainConnection);
}
else
{
socket.Close(); // Doesn't release all the handles!!!
socket = null;
}
}

The problem is that even though I close my socket when it fails to
connect, the handle count keeps going up. From the post mentionned
above, this doesn't seem to be a leak but the way the GC manage the
lifetime of the handles. After a certain time where the handle count
can reach a really high number, the GC will release a bunch of them.

My questions are: How can you determine that you really are confronted
to a handle leak when you never know when the GC will release the
handle? Is there a way to tell the GC to always release the handle when
requested by the code for testing purpose? If I do not call Close() on
the socket, will it really leak or is the GC will eventually release
the handle?

Best regards,
Jonathan
 
Well, after isolating the problem further more it seems that the leak
doesn't occur at this point. I guess that the behaviour described in
the link I was referencing to in my precedent post is not vaild
anymore.

But still I was wondering if the GC can hold a reference to a handle
even though an object that was holding this reference was diposed
correctly?
 
I notice you only call socket.EmdConnect(ar) if the connect succeeds.
Didn't you say that it usually fails?

What happens if you try to call EndConnect whether or not it succeeds?

Cheers -

Simon

private void Socket_AcceptConnectCallback(IAsyncResult ar)
{
Socket socket = (Socket)ar.AsyncState;

if( socket==null )
return;

if ( socket.Connected)
{
socket.EndConnect(ar);
// Connection succeeded
CreateNewConnection(socket, out
m_iClientMainConnection);
}
else
{

// always call end for async functions
socket.EndConnect(ar);
 
Yes I have tried it but I have an SocketException with the messge: "No
connection could be made because the target machine actively refused
it". So I figured that it should only be called when the connection
succeed.

Jonathan
 
Back
Top