Thread中的MessageLoop

San*_*ira 12 delphi delphi-xe2

如何使用OTL在线程中实现消息循环?Application.ProcessMessages; 是我到目前为止使用的,但使用它并不是很安全.

谢谢

Dav*_*nan 17

这是我从线程队列中提取消息的方式:

while GetMessage(Msg, 0, 0, 0) and not Terminated do begin
  Try
    TranslateMessage(Msg);
    DispatchMessage(Msg);
  Except
    Application.HandleException(Self);
  End;
end;
Run Code Online (Sandbox Code Playgroud)

使用Application.ProcessMessages将拉取调用线程队列的消息.但是在消息循环中使用它是不合适的,因为它不会阻塞.这就是你使用的原因GetMessage.如果队列为空,它会阻塞.并且Application.ProcessMessages还调用其他TApplication未设计为线程安全的方法.所以有很多理由不从主线程以外的线程调用它.

当你需要终止线程时,我这样做:

Terminate;
PostThreadMessage(ThreadID, WM_NULL, 0, 0);
//wake the thread so that it can notice that it has terminated
Run Code Online (Sandbox Code Playgroud)

这些都不是特定于OTL的.这段代码都旨在生活在TThread后代.但是,这些想法是可以转让的.


在注释中,您指示您要运行繁忙的非阻塞消息循环.你会用PeekMessage它.

while PeekMessage(Msg, 0, 0, 0, PM_REMOVE) do begin
  Try
    TranslateMessage(Msg);
    DispatchMessage(Msg);
  Except
    Application.HandleException(Self);
  End;
end;
Run Code Online (Sandbox Code Playgroud)