简体   繁体   中英

Why can't you access Windows GUI from a background thread?

I know that in a Windows application background threads are not allowed to directly access GUI items. What I don't fully understand is why. The closest explanation I have found is this one:

Access to Windows Forms controls is not inherently thread safe. If you have two or more threads manipulating the state of a control, it is possible to force the control into an inconsistent state. Other thread-related bugs are possible, such as race conditions and deadlocks. It is important to make sure that access to your controls is performed in a thread-safe way.

which is from this MS documenation .

Can anybody elaborate on a specific example of what two threads could do that would put a window item into an inconsistent state?

Winforms and WPF are not thread-safe because Windows windows are not thread-safe. In general, large amounts of code with lots of state are never thread-safe, it is just too hard to make the so. It isn't limited to user32 and gdi32, a browser isn't thread-safe either for example. Even if Microsoft went through extraordinary lengths to make windows thread-safe, it would still not work well in practice. Because that doesn't automatically make your code thread-safe. You'd still fight glitches if threads do not coordinate to determine what a window should look like. A very hard to solve problem, I have the scars to prove it. The universal solution is to make only one thread responsible for its content.

In Windows, only kernel32 is thread-safe. Necessarily so, you wouldn't be able to safely use threads if that wasn't the case. You see this back in the kernel32 api functions, they do very small things that affect very little state.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM