我有一个在 Windows XP SP3 x86 上运行的 Visual Studio 2008 C# .NET 3.5 应用程序。在我的应用程序中,我有一个OnSendTask
可以由多个线程同时调用的事件处理程序。它打开到远程主机的 TCP 连接并发送/接收数据。
例如:
/// <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();
}
}
不幸的是,我偶尔会看到这个错误:
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)
一些信息点:
- 如果我向 40 个遥控器发送任务,我会在 6 左右看到这个响应。
- Wireshark 跟踪显示甚至没有尝试启动从 PC 到远程的 TCP 连接。
- 我可以从 PC 上 ping 遥控器并获得一致的良好响应。
- 遥控器都与运行此应用程序的 PC 位于同一交换机和子网中。途中没有花哨的网络。
任何人都可以建议可能导致此错误的原因或我该如何解决?
谢谢