为什么单独线程中的 TidTCPClient 会阻塞主线程?
一个单独的线程创建一个 TidTCPClient 和一个 TTimer。 TTimer 设置为 3 秒,如果 TCPClient 未连接,则调用 TCPClient.Connect。
如果没有可连接的服务器,则会每 3 秒尝试连接一次。
主线程(UI)什么都不做,但是如果我用鼠标抓住窗口并在屏幕上缓慢移动它,它会每 3 秒卡住大约 2 秒,然后它跳到鼠标光标位置并跟随鼠标再次尝试,直到发生下一次连接尝试。
换句话说,当 TCPClient 尝试连接时,主线程似乎被阻塞。
即使 TCPClient 位于单独的线程中,为什么会发生这种情况?
A separate thread creates a TidTCPClient and a TTimer. The TTimer is set to 3s and if the TCPClient is not connected, it calls TCPClient.Connect.
If there is no server to connect to, this results in an attempt to connect every 3 seconds.
The main thread (UI) does nothing, but if I grab the window with the mouse and move it slowly across the screen, it get's stuck every 3 seconds for about 2 seconds, then it jumps to the mouse-cursor position and follows the mouse again, until the next attempt to connect occurs.
In other words, the main thread seems to be blocked when the TCPClient tries to connect.
Why does this happen, even though the TCPClient is in it's separate thread?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你的 TTimer 通过接收 WM_TIMER 消息来工作;这些消息是在 VCL 线程中使用 VCL 的主消息泵进行分派的。 3 秒到期后,您的 TTimer.OnTimer 事件在主线程中运行,因此对 Connect 的调用在主 VCL 线程中运行。
你被阻塞是因为你没有线程!
Your TTimer works by receiving WM_TIMER messages; Those messages are dispatched using the VCL's main message pump, in the VCL threads. After the 3 seconds expire your TTimer.OnTimer event runs in the main thread, so the call to
Connect
runs in the main VCL thread.You get blocked because you're not threading!