What happens to pending messages for a window that has been destroyed?

和自甴很熟 提交于 2019-12-06 04:11:49

问题


What happens when a window is destroyed while there are still messages pending for it?

Consider the following scenario:

There are three threads, A, B, and C. Thread C owns a window.

Threads A and B use SendMessage to post messages to the window. The message from A arrives first. While C is processing the message from A, it destroys its window using DestroyWindow.

What happens to the message from thread B? Does the call by thread B to SendMessage return?

How does this work internally?


回答1:


According to MSDN, DestroyWindow "[...], flushes the thread message queue, [...]". I was not sure whether this meant processing the messages or dumping them, so I tried. It turned out to be the latter: all pending posted messages are removed from the queue and ignored. As for non-queued messages: in my tests the pending SendMessage call returned and set the last error to ERROR_INVALID_PARAMETER - 87 (0x57).




回答2:


In principle, what you're proposing to do isn't safe. There's no way for thread C to guarantee that thread B has already sent the message; if the window is destroyed before thread B sends the message, and if the window handle happens to get reused in the meantime, thread B might wind up sending the message to the wrong window, which might be in a different application.

The best practice would be to make sure that all threads have been informed that a particular window handle has become invalid before calling DestroyWindow.

However, practically speaking, the risk of the handle being reused at just the wrong time is very low. If it is not plausible to inform the other threads ahead of time, you are unlikely to get into trouble as a result. I believe that kicsit is right in asserting that the message will not end up waiting in thread C's message queue, although the documentation does not explicitly promise this as far as I can tell.



来源:https://stackoverflow.com/questions/11203231/what-happens-to-pending-messages-for-a-window-that-has-been-destroyed

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!