473,287 Members | 1,663 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,287 software developers and data experts.

Handle leak in Socket.BeginConnect()

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.
Nov 15 '05 #1
2 7946
Bryan,

The problem comes from the fact that you are never closing the socket if
the connection succeeds. The variable y holds the socket in the
StartConnect method, and goes out of scope. However, you have passed it
along as the AsyncState for the asynchronous operation.

Then, in the AsyncConnectComplete method, you only call Close if there
is an error. You should place the call to Close (or Dispose) in a finally
clause, so that it is always disposed of. You only try and call EndConnect,
and that does not dispose of the socket.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Bryan Mayland" <bm******@tehinternet.com> wrote in message
news:g3********************************@4ax.com...
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.

Nov 15 '05 #2
Actually I should have specified. In the short test code I posted
I've removed the extra code. I know that you're supposed to actually
do something with the socket once it connected. The test code is
supposed to never actually get a connection, since I have no problems
if the socket actually connects.

If it does connect, then yes it will leak, but for testing purposes
you have to make sure the connect fails ever time.

On Fri, 31 Oct 2003 08:57:23 -0500, "Nicholas Paldino [.NET/C# MVP]"
<mv*@spam.guard.caspershouse.com> wrote:
Bryan,

The problem comes from the fact that you are never closing the socket if
the connection succeeds. The variable y holds the socket in the
StartConnect method, and goes out of scope. However, you have passed it
along as the AsyncState for the asynchronous operation.

Then, in the AsyncConnectComplete method, you only call Close if there
is an error. You should place the call to Close (or Dispose) in a finally
clause, so that it is always disposed of. You only try and call EndConnect,
and that does not dispose of the socket.

Hope this helps.


Nov 15 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Yair | last post by:
Hello, I've encounter a leak of 50 handles, when trying to query performance counters through the registry using HKEY_PERFORMANCE_DATA registry key. I've found out that when netfxperf.dll is...
12
by: Ken Brubaker | last post by:
I am using DB2 8.5 FP5 on Windows 2000 Server and have noticed what appears to be a handle leak. When I execute a DB2 connect statement in a command window, followed by a DB2 connect reset...
2
by: Peter Chapman | last post by:
Hi I am using the BeginConnect function on my socket but I am not exactly sure how I am supposed to clean up after this call. After the connecion attempt has completed I call EndConnect passing...
10
by: Manfred Braun | last post by:
Hi All, I am writing a proggi, which should monitor some processes. While doing this, I needed a test-program and wrote one, which does nothing else than to consume some cpu, sometimes more,...
3
by: Jayme Pechan | last post by:
I was wondering if someone could help me understand why it seems that creating threads using the code below causes handles to seemingly leak. System.Threading.Thread threadRunAsync = new...
4
by: NickP | last post by:
Hi there, This is really crazy! 1. Make a folder 2. Put a text file in the folder 3. Run the following code... Dim pop As New OpenFileDialog Using pop
0
by: PlayQ | last post by:
Hello, I am using the C# example code in the WMEncoder Series 9 SDK to encode a series of audio files but after a while I notice a handle leak in the system. The handle count keeps going up until...
2
by: semedao | last post by:
Hi , someone know the reason and how to handle it? thanks
1
by: =?Utf-8?B?QU1lcmNlcg==?= | last post by:
I have a vb.net program that leaks handles as reported by task manager. After running for a couple of hours, task manager reports over 1000 handles, and it continues to grow. I think I am failing...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.