multithreading - 帖子线程消息 : Create a message queue

标签 multithreading delphi delphi-10.2-tokyo

我有一个关于线程在其生命周期开始时缺少消息队列的问题。 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) 解决了我的问题,对 PostThreadMethod() 的第二次调用在我的应用程序中始终成功。

但是,我想理解第二种方法,但根本不理解“事件对象”(当然不是普通的Delphi事件?)“到有信号状态”和“将事件设置为指示”。

问题:有人可以将第 (2) 段翻译成简短的 Delphi 代码示例吗?

最佳答案

这些事件对象是同步对象,MSDN 中对此进行了描述:Event Objects

该主题的底部是指向 Using Event Objects 的链接。其中提供了示例代码,展示了如何创建事件、设置事件、等待事件等。

简而言之,您使用以下功能:

  • CreateEvent 创建事件对象。
  • CloseHandle 以销毁它。
  • SetEventResetEvent 用于设置和重置事件对象。
  • WaitForSingleObject 等待收到信号。

您可以使用TEvent System.SyncObjs 单元中的类来包装所有这些低级 API 调用。那么流程就会变成这样:

  • 创建一个 TEvent 对象,例如处于重置状态的 Event
  • 创建工作线程,传入Event
  • 在管理器线程中调用 Event.WaitFor 以等待工作线程发出其消息队列存在的信号。
  • 当工作线程开始执行时(即在其 Execute 方法开始时),让它创建消息队列,然后通过调用 Event.SetEvent 设置事件>.

关于multithreading - 帖子线程消息 : Create a message queue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49610544/

相关文章:

multithreading - 为什么 Go 的 LockOSThread 不锁定这个 OS 线程?

java - 有人能解释一下这个Java线程池吗?

python - 线程中未标记的异常

c - 当按值传递静态变量时会导致 c 中的竞争条件

delphi - 为什么在TObject中使用“T”前缀?

delphi - 如何在 Spring4D 1.2 中更新数据库架构

delphi - 调试包含字符串的 TValue

delphi - 如何在不修改给定单元的情况下禁用该单元的警告?

德尔福 Firedac 甲骨文 : Raises Exception When Locating Primary key (VARCHAR or VARCHAR2)

java - 将 Java .class 文件传递​​给 Delphi Constructor