gpt4 book ai didi

multithreading - Delphi 中 CPU 使用率 100%

转载 作者:行者123 更新时间:2023-12-03 15:05:33 35 4
gpt4 key购买 nike

我使用 Indy 9 和 Delphi 5。在我的应用程序中,我想通过 UDP 与网络设备通信。所以我使用UDPServer comp。在从 TThread 派生的类中。当我编写类似以下代码时,CPU 使用率为 100%。

在线程中:

while not terminated do begin
if GetMessage(Msg, 0, 0, 0) then begin
if Msg.message = WM_UDPMSG then
Break
else
DispatchMessage(Msg);
end;
end;

和 OnUDPRead 事件:

  try    
// Processing the data here
except
PostThreadMessage(ThreadId, WM_UDPMSG, 0, 0);
end;

当我在 while-do 循环或 OnUDPRead 事件中使用 Sleep 函数时,没有任何变化。 CPU 使用率仍然是 100%。

我的线程优先级是正常。

如何解决我的问题?

最佳答案

您遇到的问题是因为您在 GUI 线程中接收 UDP 数据,但想要在另一个线程中处理该数据。

真正的问题是您尝试以阻塞方式使用异步组件。更好的解决方案是使用真正的阻塞 UDP 通信库,例如 synapse 。然后就很容易等待线程中接收新数据。

你可以这样写:

while not Terminated do
begin
BytesRead := FSocker.RecvBufferEx(@(Buffer[0]), BufferSize, Timeout);
if (BytesRead = 0) then
begin
// continue or exit if the receiving Failed
case FSocket.LastError of
0, WSAETIMEDOUT: Continue;
WSAECONNRESET, WSAENETRESET,
WSAENOTCONN, WSAECONNABORTED,
WSAENETDOWN:
begin
CloseConnection;
Exit;
end;
else
CloseConnection;
Exit;
end;
end;
// process the data in the buffer
end;

关于multithreading - Delphi 中 CPU 使用率 100%,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/510559/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com