ZijingWu
ZijingWu

Reputation: 3490

Is the Windows message queue handle the message in an FIFO way?

I assume when we call SendMessage & PostMessage, the message will be handled in the same order as the Send/PostMessage called. But as the document says the SendMessage will execute the function if the current thread is the correct one.

If the specified window was created by the calling thread, the window procedure is called immediately as a subroutine.

So in following case:

PostMessage(currentThreadWindow, postMsg, ...) // line 1
SendMessage(currentThreadWindow, sendMsg...) // line 2

the sendMsg will be handled before postMsg.

So does message passed to SendMessage and PostMessage keep the order?

Upvotes: 0

Views: 682

Answers (1)

IInspectable
IInspectable

Reputation: 51355

So does message passed to SendMessage and PostMessage keep the order?

You already know the answer to this question, if you are sending/posting a message to a window owned by the calling thread: The call to SendMessage bypasses the message queue altogether, and calls the window procedure immediately, so this message will always be handled prior to a posted message.

If you are crossing thread boundaries, you don't get any guarantees anymore. Even though in-bound cross-thread messages are dispatched before any messages currently in the message queue, you cannot control when the calling thread gets preempted. If it gets preempted in between the calls to PostMessage and SendMessage, the posted message is likely to be handled before the sent message. If the calling thread doesn't get preempted in between those calls, you still don't get any guarantees. It depends on the concurrently executing receiving thread, whether the posted or sent message is handled first.

To complicate things further, a thread can receive messages at other times as well (see When can a thread receive window messages?). While waiting for the result of an out-bound SendMessage-call, a thread will still receive in-bound cross-thread messages. In other words: You cannot even rely on the fact, that messages are handled as a whole, before moving on to the next message. Your window procedure needs to be prepared for re-entrancy.

What you can rely upon is, that the relative order of several posted messages is maintained. If you post 2 messages the first of those messages is handled prior to the second message. Those messages can still be interspersed with other posted messages.

Upvotes: 3

Related Questions