Sim*_*aWB 5 delphi multithreading udp
我使用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;
Run Code Online (Sandbox Code Playgroud)
和OnUDPRead事件:
try
// Processing the data here
except
PostThreadMessage(ThreadId, WM_UDPMSG, 0, 0);
end;
Run Code Online (Sandbox Code Playgroud)
当我在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;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3453 次 |
| 最近记录: |