Don’t Use the Win32 API PostThreadMessage() to Post Messages to UI Threads

  不要用Win32 API PostThreadMessage()向UI线程发送消息。

  

  PostThreadMessage is a Win32 API used to post messages to threads. Usually, the message posted is a standard windows message with the window handle set to NULL.

  PostThreadMessage是一个Win32 API常用于向线程发送消息。通常,这个被发送的消息是个窗口句柄被设为NULL的,标准的窗口消息。

  When PostThreadMessage is used to post messages to a thread that has created a window, it is very likely that the posted messages will be lost. This is because UI threads are not always run by the primary message loop. For example, when a thread is showing a message box, it is running on the message loop supplied by the message box. This secondary message loop does not know how to handle the thread message (since its window handle is NULL) and it will be dropped.

  当你将PostThreadMessage用于向一个创建窗口的线程发送消息,结果这个消息很可能会丢失。这是因为UI线程并非总是在一级消息循环中。例如,当一个线程正显示一个消息对话框,它就运行在这个消息对话框提供的(代理的)消息循环中。这个二级消息循环不知如何处理这个线程消息(因为其窗口句柄是NULL)所以它会被放弃。

  So when posting messages to a UI threads, use PostMessage() instead and post messages to a window owned by that thread. Then the messages won’t be lost, even if the thread is running a secondary message loop.

  因此,当要发送一个消息给UI线程,就用PostMessage()作替代并向线程自己的窗口发消息。这样消息就不会被丢失,即便这个消息是运行在二级消息循环中。