简体   繁体   English

为什么不能从后台线程访问Windows GUI?

[英]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. 我知道在Windows应用程序中,后台线程不允许直接访问GUI项。 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. 对Windows窗体控件的访问本质上不是线程安全的。 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 . 这是来自MS的文件

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. Winforms和WPF不是线程安全的,因为Windows窗口不是线程安全的。 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. 它不仅限于user32和gdi32,例如浏览器也不是线程安全的。 Even if Microsoft went through extraordinary lengths to make windows thread-safe, it would still not work well in practice. 即使微软花了很大的篇幅来保证Windows的线程安全,它在实践中仍然无法正常工作。 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. 在Windows中,只有kernel32是线程安全的。 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. 你在kernel32 api函数中看到了这个,它们会做很小的事情,影响非常小的状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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