Krzysztof Bracha
Krzysztof Bracha

Reputation: 913

Why is SendMessage designed to behave different in a window's procedure than in worker threads?

At first I would ask you to please don't misunderstand the question. I'm not asking how does SendMessage works, but why was it designed to work the way it does. Basically, I'm wondering why couldn't the call to a window procedure be made directly from a worker thread, the same way it is made from the window thread, instead of a message being pumped into the message queue?

In a very simple case in a worker thread I could just do:

WndProc(hWnd,MY_MESSAGE,wParam,lParam);

instead of:

SendMessage(hWnd,MY_MESSAGE,wParam,lParam);

and get the response immediately. Are there any drawbacks when you just call WndProc directly?

I can understand that things get more complicated, when you would like to send a message to a window that is owned by another process, but couldn't there exist a SendMessage-like function that works the same in a worker thread like in the window thread? Is there any reason behind that there doesn't exist any? Thank you in advance for any explanation.

Upvotes: 0

Views: 439

Answers (1)

Steve
Steve

Reputation: 7271

The writers of window procedures expect all of the calls to be made on one thread. By using SendMessage, the message can be placed on a (thread-safe) queue. A single thread can take the messages off the queue and pass them to the window procedure.

The drawback is that calling WndProc from another thread introduces race conditions. Certain UI objects have thread affinity. If that is not respected (e.g. by calling WndProc from another thread) then this can cause issues. Device contexts are an example of this. According to Raymond Chen

Window objects have thread affinity. The thread that creates a window is the one with which the window has an inseparable relationship. Informally, one says that the thread "owns" the window. Messages are dispatched to a window procedure only on the thread that owns it, and generally speaking, modifications to a window should be made only from the thread that owns it. Although the window manager permits any thread to access such things as window properties, styles, and other attributes such as the window procedure, and such accesses are thread safe from the window manager's point of view, load-modify-write sequences should typically be restricted to the owner thread. Otherwise you run into race conditions...

Upvotes: 6

Related Questions