How to exit a thread's message loop?

前端 未结 2 548
难免孤独
难免孤独 2021-02-02 16:35

A background-thread can be configured to receive window messages. You would post messages to the thread using PostThreadMessage. What\'s the correct way to exit that message loo

相关标签:
2条回答
  • 2021-02-02 17:25

    Using PostThreadMessage is not necessarily incorrect. Raymond's article that you linked to says:

    Because the system tries not to inject a WM_QUIT message at a "bad time"; instead it waits for things to "settle down" before generating the WM_QUIT message, thereby reducing the chances that the program might be in the middle of a multi-step procedure triggered by a sequence of posted messages.

    If the concerns outlined here do not apply to your message queue, then call PostThreadMessage with WM_QUIT and knock yourself out. Otherwise you'll need to create a special signal, i.e. a user-defined message, that allows you to call PostQuitMessage from the thread.

    0 讨论(0)
  • 2021-02-02 17:26

    There is no canonical way; there is no canon. You get GetMessage to return zero by posting a wm_Quit message, and you do that by calling PostQuitMessage. When and how you know to do that is up to you.

    It common to do it in response to wm_Destroy, but that's only because the common way to exit programs is by closing windows. If you have no window to close, then choose a different way. Your wm_PleaseEndYourself idea is fine.

    You don't even have to send a message. You could use some waitable object like an event or a semaphore, and then use MsgWaitForMultipleObjects to detect whether it's signaled while also waiting for new messages.

    You don't really even have to wait for GetMessage to return zero. If you already know the thread needs to stop, then you can simply stop processing messages entirely. There are lots of ways to exit a loop. You could use exit, break, raise, or even goto, or you could set a flag that you check in the loop condition along with the return value of GetMessage.

    Note also that GetMessage returns -1 on failure, which as a non-zero value will be interpreted as true. You probably don't want to continue your message loop if GetMessage fails, so instead check for GetMessage(...) > 0, or do like the documentation recommends.

    0 讨论(0)
提交回复
热议问题