PostThreadMessage: Create a message queue
我有一个关于线程在其生命周期开始时缺少消息队列的问题。 MSDN解释
The thread to which the message is posted must have created a message queue, or else the call to PostThreadMessage fails. Use one of the following methods to handle this situation:
(1) Call PostThreadMessage. If it fails, call the Sleep function and call PostThreadMessage again. Repeat until PostThreadMessage succeeds.
(2) Create an event object, then create the thread. Use the WaitForSingleObject function to wait for the event to be set to the signaled state before calling PostThreadMessage. In the thread to which the message will be posted, call
PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE) to force the system to create the message queue. Set the event, to indicate that the thread is ready to receive posted messages.
方法(1)解决了我的问题,对
但是,我想理解第二种方法,只是根本不理解"事件对象"(肯定不是正常的Delphi事件?)"处于信号状态"和"将事件设置为指示"。
问题:有人能将第(2)段翻译成简短的Delphi代码示例吗?
这些事件对象是同步对象,在MSDN的此处描述:事件对象。
该主题的底部是"使用事件对象"的链接,该链接提供了示例代码,显示了如何创建事件,设置事件,等待事件等。
简而言之,您可以使用以下功能:
-
CreateEvent 创建事件对象。 -
CloseHandle 销毁它。 -
SetEvent 和ResetEvent 来设置和重置事件对象。 -
WaitForSingleObject 等待它被发信号。
您可以使用
-
在重置状态下创建一个
TEvent 对象,例如Event 。 -
创建工作线程,传入
Event 。 -
在管理器线程中调用
Event.WaitFor 以等待工作线程发出其消息队列存在的信号。 -
当工作线程开始执行时(即在其
Execute 方法的开始处),让它创建其消息队列,然后通过调用Event.SetEvent 设置事件。