I have a Visual Studio 2008 C# .NET 3.5 application running on Windows XP SP3 x86. In my application, I have an event handler OnSendTask that can be called by multiple threads simultaneously. It opens a TCP connection to a remote host and sends/receives data.
For example:
/// <summary>
/// prevent us from exceeding the maximum number of half-open TCP
/// connections in Windows XP.
/// </summary>
private System.Threading.Semaphore tcp_connection_lock_ =
new System.Threading.Semaphore(10, 10);
public event EventHandler<SendTaskEventArgs> SendTask;
private void OnSendTask(object sender, SendTaskEventArgs args)
{
try
{
tcp_connection_lock_.WaitOne();
using (TcpClient recipient = new TcpClient())
{
// error here!
recipient.Connect(args.IPAddress, args.Port);
using (NetworkStream stream = recipient.GetStream())
{
// read/write data
}
}
catch
{
// write exceptions to the logfile
}
finally
{
tcp_connection_lock_.Release();
}
}
void SendTasks(int tasks_to_send)
{
using (ManualResetEvent done_event = new ManualResetEvent(false))
{
int countdown = tasks_to_send;
for (int i = 0; i < tasks_to_send; ++i)
{
ThreadPool.QueueUserWorkItem((o) =>
{
SendTaskEventArgs args = new SendTaskEventArgs(/*...*/);
EventHandler<SendTaskEventArgs> evt = SendTask;
if (evt != null)
evt(this, e);
if (Interlocked.Decrement(ref countdown) == 0)
done_event.Set();
}, i);
}
done_event.WaitOne();
}
}
Unfortunately, I occasionally see this error:
System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 192.168.0.16:59596
at System.Net.Sockets.TcpClient.Connect(String hostname, Int32 port)
Some points of information:
- If I send a task to 40 remotes, I will see this response from around 6.
- A Wireshark trace shows no attempt to even initiate a TCP connection from the PC to the remote.
- I can ping the remote from the PC and get consistent good responses.
- The remotes are all on the same switch and subnet as the PC running this application. There is no fancy networking in the way.
Can anybody suggest what may be causing this error or how I can fix it?
Thanks
I am not sure of all of the details behind the max half-open TCP connections but, I believe it is NOT specific to application connections, but rather system wide. Are you sure that when this error occurs there are no other applications on the system that are creating TCP connections?
I’d setup a retry whenever an error occurs. Something like: