B
Bryan Mayland
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. If left retrying over
a long period of time the extra handles build up to several thousand
quite quickly. 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);
}
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().
Is there something I'm missing here? Calling GC.Collect() all the
time is a terrible solution to this problem.
connect. Each time I attempt a connection, 3 handles are allocated,
and when the connect fails 2 handles are freed. If left retrying over
a long period of time the extra handles build up to several thousand
quite quickly. 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);
}
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().
Is there something I'm missing here? Calling GC.Collect() all the
time is a terrible solution to this problem.