A customer had a program that created a window, then posted a message to it. They were surprised to find that the message was dispatched too soon. Specifically, it was dispatched before the program reached its main message loop, which is a problem because there is other preparatory work that happens after the window is created but before the program reaches its main message loop, and the premature dispatch of the posted message is causing the message handler to do things before all the preparatory work is completed.
The customer was under the impression that posted messages aren’t dispatched until the main message loop starts processing them. Why is the posted message being dispatched too soon, and what can they do to fix it?
You have all the clues to solve the mystery in their problem description.
First, we get to dispel the customer’s misconception. There is no rule that says that posted messages wait for the main message loop to process and dispatch them. Posted messages are dispatched whenever anybody calls GetÂMessage or PeekÂMessage to retrieve the posted message, and then passes that posted message to the DispatchÂMessage function. Anybody could perform these operations; it doesn’t have to be the main message loop.
Indeed, the system doesn’t know which message loop is your “main” message loop. It’s not like the system finds the calling code, reverse-compiles it, does semantic analysis, and then says, “Aha, I think this one is the main message loop.” (Indeed, I’ve written programs where there is no “main” message loop.)
The clue here is that they say that they have “preparatory work”.
I bet that some of their preparatory work goes into a little message loop. Maybe it posts a message to another window and pumps messages while waiting for a response. (For example, it might be doing DDE.) Or maybe it makes a cross-process COM call, because cross-process COM calls from single-threaded apartments pump messages while waiting for the call to complete.
The customer could confirm this theory by setting a breakpoint on their message handler and taking a stack trace to see what call they are making that is leading to messages being pumped.
The fix is not to post the message until all the preparations are complete. In other words, to prevent the message from arriving too soon, don’t post it too soon.
Bonus reading: Why are my posted messages getting lost when the user drags my window around?
0 comments
Be the first to start the discussion.