user1803300
user1803300

Reputation:

How do i forcibly process messages inside a thread?

Despite having Application.ProcessMessages, which is only for the Main VCL Thread, is there a similiar method for a TThread class ? or how can i write one on my own ?

lets say that on the client side i use SendBuf 2 times...

SendBuf(....
SendBuf(....

on server side, OnRead gets fired 2 times, but between us i have already read the socket buffer in a single OnRead call, so how do i avoid the 2nd one without exceptions ? the only way i can think of is process the messages in the message queue so they'd get out of there already and won't fire that event again. (do it while reading)

Upvotes: 0

Views: 2656

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 598134

If you want to process messages in a worker thread, you have to run a message loop manually, eg:

procedure TMyThread.Execute;
var
  Msg: TMsg;
begin
  ...
  while GetMessage(Msg, 0, 0, 0) > 0 then
  begin
    TranslateMessage(Msg);
    DispatchMessage(Msg);
  end;
  ...
end;

Or:

procedure TMyThread.Execute;
var
  Msg: TMsg;
begin
  ...
  while not Terminated do
  begin
    ...
    if PeekMessage(Msg, 0, 0, 0, PM_REMOVE) then
    begin
      TranslateMessage(Msg);
      DispatchMessage(Msg);
    end;
    ...
  end;
  ...
end;

Or:

procedure TMyThread.Execute;
var
  Msg: TMsg;
begin
  ...
  while not Terminated do
  begin
    ...
    if MsgWaitForMultipleObjects(0, nil, FALSE, SomeTimeout, QS_ALLINPUT) = WAIT_OBJECT_0 then
    begin
      while PeekMessage(Msg, 0, 0, 0, PM_REMOVE) do
      begin
        TranslateMessage(Msg);
        DispatchMessage(Msg);
      end;
    end;
    ...
  end;
  ...
end;

Upvotes: 8

Related Questions