CWnd Derived MFC Objects and Multi-Threaded Applications

xiaoxiao2021-03-06  40

Summary

In a multi-threaded application written using MFC, you should not pass MFC objects across thread boundaries. As a general rule, a thread should access only those MFC objects that it creates. Failure to do so may cause run-time problems including assertions or UNEXPECTED Program Behavior.

More information

In a Win32 Process, All The Threads Running in The Process Address Space Can View All Global and static data. A Thread Can Use thread-local-storage (tls) To store Any Thread-Specific Data.

In a multi-threaded environment because windows are owned by threads, MFC keeps the temporary and permanent window handle map in thread local storage. The same is true for other handle maps like those for GDI objects and device contexts. Keeping the window handle maps in Thread Local Storage Ensures Protection Against Simultaneous Access by Several Threads.

The behavior of the functions CHandleMap :: LookupPermanent () and CHandleMap :: LookupTemporary () is a direct consequence of these facts. Given a window handle, these functions check the permanent and temporary window handle maps of the current thread for the existence of an Associated CWND Derived MFC Object. This Means That From A Thread To Search for MFC Objects That Repesent Windows Created In Other Threads, The Calls Will Fail.

There are several functions that call CHandleMap :: LookupPermanent () and CHandleMap :: LookupTemporary (). CWnd :: AssertValid () (and hence the macro ASSERT_VALID for a CWnd object) is one such function. This function is called to make validity checks on an object. If AssertValid () fails to find an entry for the MFC object's m_hWnd member in any of the handle maps or finds an incorrect entry, it fires an assertion. in Visual C 2.1, these assertions are in file wincore.cpp, lines 797 and 798. in Visual C 2.2, they are in wincore.cpp, lines 804 and 805. in Visual C 4.0, they are in wincore.cpp, lines 871 and 872.Calls to the ASSERT_VALID macro are sprinkled all over the MFC source code. Hence, from a particular thread, if you end up calling a function that calls ASSERT_VALID on MFC window objects that belong to some other thread, you get an assertion. If you do not get an assertion, you may still get abnormal behavior Because you are not allowing to directly manipulate windows create Other threads.

The correct approach in such situations is to work with window handles, not MFC objects. It is safe to pass window handles across thread boundaries. If thread A passes a window handle to thread B, then thread B can use this window handle to send or POST Messages to the window. When these Messages Are Processed, You Are Back In The Context of Thread A and calls to cwnd :: assertvalid () to check thread a's window handle map will succe.

转载请注明原文地址:https://www.9cbs.com/read-75842.html

New Post(0)