线程内的MessageLoop [英] MessageLoop within Thread
问题描述
如何使用OTL在线程内实现消息循环? Application.ProcessMessages;是我到目前为止所使用的,但是使用它并不是很安全。
How can I implement a message loop within a thread using OTL? Application.ProcessMessages; is what i used so far but it isn't very safe to use it.
谢谢
推荐答案
这是我从线程的消息中提取消息的方法队列:
This is how I pull messages off a thread's queue:
while GetMessage(Msg, 0, 0, 0) and not Terminated do begin
Try
TranslateMessage(Msg);
DispatchMessage(Msg);
Except
Application.HandleException(Self);
End;
end;
使用 Application.ProcessMessages
将提取以下消息调用线程的队列。但是不适合在消息循环中使用,因为它不会阻塞。这就是为什么您使用 GetMessage
的原因。如果队列为空,它将阻塞。并且 Application.ProcessMessages
还会调用其他 TApplication
方法,这些方法不是线程安全的。因此,有很多理由不从主线程以外的其他线程调用它。
Using Application.ProcessMessages
will pull messages of the queue of the calling thread. But it's not appropriate to use in a message loop because it won't block. That's why you use GetMessage
. It blocks if the queue is empty. And Application.ProcessMessages
also calls other TApplication
methods that are not designed to be thread safe. So there are plenty of reasons not to call it from a thread other than the main thread.
当您需要终止线程时,我可以这样做:
When you need to terminate the thread, then I do this:
Terminate;
PostThreadMessage(ThreadID, WM_NULL, 0, 0);
//wake the thread so that it can notice that it has terminated
没有一个特定于OTL。这段代码全部旨在包含在 TThread
后代中。但是,这些想法是可以转移的。
None of this is OTL specific. This code all is intended to live in a TThread
descendent. However, the ideas are transferable.
在注释中,您指示您要运行忙碌且不阻塞的消息循环。您将为此使用 PeekMessage
。
In the comments you indicate that you want to run a busy, non-blocking message loop. You would use PeekMessage
for that.
while PeekMessage(Msg, 0, 0, 0, PM_REMOVE) do begin
Try
TranslateMessage(Msg);
DispatchMessage(Msg);
Except
Application.HandleException(Self);
End;
end;
这篇关于线程内的MessageLoop的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!