Search code examples
c#winformswindows-messagesmessage-pump

GUI message queues (message pump - parallel or series)


I can't seem to find an answer to this anywhere. I'm not sure if I know how to phrase it.

Do messages destined for controls on a form process in parallel to each other?

I was always under the impression we had one message pump per thread apartment, and that one pump would feed the entire GUI attached to that thread. So if you hooked into the wndproc on one control and froze the thread (Thread.Sleep()), the entire form would freeze?

If so, this question appears to prove that by sleeping when a particular message arrived on a child control, an adjacent control processed its next message. How?


Solution

  • Messages are processed strictly serially. Don't be mislead by the timestamps in that Q+A, it just doesn't have enough digits in the fraction to show that the messages actually arrived micro-seconds apart. The message handlers are very quick, that's normal.

    Code only ever runs in parallel when you have multiple threads. That's poison to a user interface, large chunks of code are never thread-safe. Even small chunks, very basic .NET classes like List<> are not. You keep code thread-safe by using locking, the hard way and something you only ever have a shot at with small code, or by ensuring that it always runs on one specific thread.

    The message loop exists because UI is not thread-safe. It is the universal solution to the producer-consumer problem. Threads in the operating system and other processes produce, the UI thread consumes.