100% CPU usage in Delphi

I am using Indy 9 with Delphi 5. In my application, I want to communicate with a network device via UDP. Therefore, I am using the UDPServer comp. in a class that is derived from TThread. When I write similarly to the following code, then the CPU usage is 100%.

in the stream:

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;

and the OnUDPRead event:

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

When I use the Sleep function in a while-do loop or in the OnUDPRead event, there is no change. However, CPU utilization is 100%.

My thread priority is Normal.

How can I solve my problem?

+5
source share
6 answers

The problem is that you are receiving UDP data in a GUI thread, but want to process the data in another thread.

, . 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;
+6

delphi, busy-wait, .

. /. , - .


:
+3

1 , Indy , 9.0.0.18. . Indy, Delphi 7.

2 , Indy.

http://www.indyproject.org/demos/index.html

+2

GetMessage, ( ), ?

+1

GetMassage. Windows.pas,

function GetMessage; external user32 name 'GetMessageA';
+1

- . . , Indy, .

I watched all the Indy demos. These demos are very simple. In my project, I have a very fast data transfer. (Like real-time sound recording)

0
source

All Articles