Handle leak in Socket.BeginConnect()/EndConnect()

  • Thread starter Bryan 'CapnBry' Mayland
  • Start date
B

Bryan 'CapnBry' Mayland

I posted this about a year ago and seeing as it is still broken in
..NET 1.1 SP1, and everyone's had a year longer to work with async
sockets, I figured I'd bring it up again.

I've got a problem with a System.Net.Socket that is failing on
connect. Each time I attempt a connection, 3 handles are allocated,
and when the connect fails 2 handles are freed. Even though one
handle per connection attempt is not a huge loss, if left retrying
over a long period of time the extra handles build up to several
thousand quite quickly. This only occurs when the connect fails,
usually due to a TIMEDOUT or CONNREFUSED winsock error.

Here's the C# code:
private void StartConnect()
{
// Allocate 1 handle for socket
Socket y = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);

IPHostEntry he = Dns.Resolve(_host);
if (he.AddressList.Length == 0)
throw new Exception("Could not resolve host " + _host);

IPEndPoint hostEndPoint = new IPEndPoint(he.AddressList[0],
_port);
// Allocate 1 handle for asyncwait
// Allocate another handle for ???
y.BeginConnect(hostEndPoint, new
AsyncCallback(AsyncConnectComplete), y);
y = null;
}

private void AsyncConnectComplete(IAsyncResult ar)
{
Socket s = (Socket)ar.AsyncState;
try
{
// Throws exception because connect failed
s.EndConnect(ar);
// code after this removed
// test case should fail connected every time
}
catch (SocketException e)
{
// Free socket handle
// Free asyncwait handle
s.Close();
s = null;
}
}

Each call to StartConnect and its subsequent failure leaves one handle
open. The handle can be recovered by forcing a garbage collection
with GC.Collect(). You can see the number of handles allocated going
up in task manager. If left running attempting a connection every 2
seconds, that's 1800 handles per hour, or about 25,000 handles if I
start it now and check it first thing tomorrow morning.

Does anyone else sucessfully use async Begin/EndConnects in the real
world (where sometimes the machine you're connecting to may be down or
the app on the other side has crashed)?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top