MFC: accessing GUI from another thread?

前端 未结 2 930
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-18 15:13

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

However is that a law or just recommended? If I make sure, via critical sections, that

相关标签:
2条回答
  • 2020-12-18 15:19

    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 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.

    0 讨论(0)
  • 2020-12-18 15:35

    I used to think its almost forbidden to access GUI from a worker thread in MFC and is a recipe for disaster. But recently I learned this is not that hard rule if you know what you are doing, you can use worker threads to access GUI. In the Win32 Multithreaded Book the provides an example of a 'self animated control' which is completely drawn in a worker thread.

    If I remember correctly the author pretty much said the same thing you said, if you critical sections at the right places you can make accessing GUI thread safe. The reason MFC doesn't do it by itself is for performance reasons.

    0 讨论(0)
提交回复
热议问题