Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostMessage: Guaranteed to be delivered?

Tags:

c++

windows

In my C++ app, I have a background thread that does some work, putting the results into a heap-allocated block of memory, and calling PostMessage to deliver the results to the Main-Thread.

Typically, when the Window receives the message, it processes the results, then does a delete on the memory specified by the lParam.

But I'm concerned that the window may exit before it gets around to processing the message and deleting the memory.

Does PostMessage somehow guarantee that the target window will get a chance to process the message?
If not, is there any well-known technique for knowing if the Window freed the memory, or if the background thread needs to be responsible for deleting it?

like image 254
abelenky Avatar asked Sep 12 '13 16:09

abelenky


People also ask

Is window postMessage secure?

Security-Reviewing Uses of postMessage()postMessage is generally considered very secure as long as the programmer is careful to check the origin and source of an arriving message. Acting on a message without verifying its source opens a vector for cross-site scripting attacks.

What is the difference between SendMessage and postMessage?

SendMessage: Sends a message and waits until the procedure which is responsible for the message finishes and returns. PostMessage: Sends a message to the message queue and returns immediately.

Is postMessage asynchronous?

The postMessage() function is asynchronous, meaning it will return immediately. So you can not do synchronous communication with it. In your example, the posted message will vanish in the void, because there is no listener for the message event at the time the postMessage() function is executed.

What does window postMessage do?

The window. postMessage() method safely enables cross-origin communication between Window objects; e.g., between a page and a pop-up that it spawned, or between a page and an iframe embedded within it.


1 Answers

PostMessage will definitely be put in the message queue of the receiving window. There is no guarantee that the window will be there, however. It could have been destroyed by that time. One way to help assure the message will get there is to create your own, hidden window (COM often uses this technique) and post to its queue. That way you have control over when the hidden window is destroyed. We employed this method for many years in real-time data delivery.

Having the background thread delete the memory is a bad idea and can lead to a race condition where it does not know when it is OK to delete. Better to post to your own window and delete it there when you are done with it.

like image 96
edtheprogrammerguy Avatar answered Sep 19 '22 12:09

edtheprogrammerguy