我用 C# 编写了一个 TCP 服务器应用程序。应用程序侦听入站连接
在主侦听器线程中使用 TcpListener.AcceptTcpClient() 方法。
当收到连接时,TcpListener.AcceptTcpClient() 解除阻塞并返回 TCPClient 对象。
收到连接后,将创建一个新线程并开始向新连接读取写入数据。
新线程由以下代码启动。
while(true)
{
TcpClient client = serverListener.AcceptTcpClient();
if (client.Connected)
{
Thread t = new Thread(delegate() { readWriteData(client); });
t.IsBackground = true;
t.Start(); /// Problem happens here. The thread gets stuck here and doesn't move further
}
}
该应用程序运行良好,但有时在 Windows 7 计算机中,该应用程序会突然停止侦听 tcp 连接。
分析该状态下的应用程序的线程堆栈(使用Microsoft stack explorer查看应用程序所有线程的堆栈)发现主侦听器线程卡在上面所示代码部分的以下行
t.Start(); /// Problem happens here. The thread gets stuck here and doesn't move further
我做了很多研究,但找不到为什么会发生这种情况。仅在 Windows 7 系统中观察到此行为。
有人可以帮我解决这个问题吗?
根据罗布的建议,
我在这里发布由windbg(sos)显示的堆栈跟踪
0547eae0 7282e006 mscorwks!Thread::StartThread+0xc3, calling mscorwks!_EH_epilog3
0547eb00 727ac825 mscorwks!__SwitchToThread+0xd, calling mscorwks!__DangerousSwitchToThread
0547eb10 728b9c6f mscorwks!ThreadNative::StartInner+0x1ba, calling mscorwks!__SwitchToThread
0547eb58 727e4b04 mscorwks!SafeHandle::DisposeNative+0x3a, calling mscorwks!LazyMachStateCaptureState
0547ebc8 728b9d80 mscorwks!ThreadNative::Start+0xa6, calling mscorwks!ThreadNative::StartInner
0547ec18 728b9d01 mscorwks!ThreadNative::Start+0x1f, calling mscorwks!LazyMachStateCaptureState
0547ec74 71de6afc (MethodDesc 0x71c13048 +0x8c System.Threading.Thread.Start()), calling mscorwks!ThreadNative::Start
0547ec8c 030e2a46 (MethodDesc 0x30da408 +0x25e WindowsService.Server.startListener()), calling (MethodDesc 0x71c13048 +0 System.Threading.Thread.Start())