我如何强制处理线程内的消息?

时间:2013-03-17 22:53:46

标签: delphi winsock

尽管Application.ProcessMessages只适用于主VCL线程,但对于TThread类是否有类似的方法?或者我怎么能自己写一个?

让我们说在客户端我使用SendBuf 2次......

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

在服务器端,OnRead被触发2次,但在我们之间我已经在单个OnRead调用中读取了套接字缓冲区,那么如何避免第二个没有例外?我能想到的唯一方法就是处理消息队列中的消息,这样他们就已经离开了那里,并且不会再次触发该事件。 (在阅读时这样做)

1 个答案:

答案 0 :(得分:7)

如果要处理工作线程中的消息,则必须手动运行消息循环,例如:

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

或者:

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;

或者:

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;