MFC:从另一个线程访问 GUI?

2022-01-12 00:00:00

所以通常只有主线程才能访问 MFC 应用程序中的 GUI.

So generally only the main thread should access the GUI in a MFC application.

但是,这是法律还是建议?如果我通过关键部分确保只有一个线程访问 GUI 中的某个对象,那么可以吗?或者,如果 MAIN 线程访问 GUI 的一部分而另一个线程访问 GUI 的一部分,这是否是一个问题.即使这两个对象不相互影响?

However is that a law or just recommended? If I make sure, via critical sections, that only one thread accesses a certain object in the GUI, is it ok then? Or is it a problem if the MAIN thread accesses one part of the GUI while another thread access one. Even if those 2 objects don't affect each other?

我问的原因是因为如果我可以从另一个线程访问 GUI,这大大简化了我对应用程序的重写.

The reason I ask is because this simplifies my rewrite of the application a lot if I can access the GUI from another thread.

推荐答案

不要这样做.如果你这样做,你将生活在一个充满断言和奇怪行为的世界中.GUI 通过在主线程上泵送"的 Windows 消息系统工作.如果您开始在另一个线程中修改 UI,您将遇到您的操作导致其他 UI 消息的情况,这些消息可能由主线程处理,同时您仍在尝试访问另一个线程上的 UI.

Don't do it. You'll live in a world of ASSERTs and weird behaviour if you do. The GUI works through a system of Windows messages which are 'pumped' on the main thread. If you start modifying the UI in another thread you'll have situations where your operation causes other UI messages, which will be handled by the main thread potentially at the same time you're still trying to access the UI on another thread.

如果不尝试处理这类事情,MFC 编程就已经够难了.而是使用 PostMessage 将 UI 相关的处理放到主线程上.

MFC programming is hard enough without trying to handle this sort of thing. Instead use PostMessage to put the UI related handling onto the main thread.

相关文章