Last Modification: December 11, 1999

Why do I get an assertion in MFC when my thread calls a function in the main thread?

The MFC message processing code is not thread-safe. So when a secondary thread calls anything in the main thread that affects a CWnd-derived object there is a danger of data corruption within MFC. To guard against this MFC uses thread local storage and liberal ASSERTs to warn you that what you are trying to do can't work reliably. There are two safe alternatives for updating a main thread window from a secondary thread. 

  1. In simple cases you can bypass MFC and take advantage of the fact that the Win32 API is thread-safe. Your secondary thread can safely use an hwnd passed from the main thread and call a Win32 function to force many kinds of updates: 
    
        // force repaint of a window in the main thread
        ::InvalidateRect(hwnd, NULL, TRUE);
    
        // change the text in any control 
        ::SetDlgItemText(hwnd, IDC_CONTROL, "New text");
    
  2. When you want to force complex actions such as UpdateAllViews or UpdateData you need the involvement of the main thread's MFC code. In such cases you can "call" the main thread from your secondary thread in a safe and synchronized fashion by sending or posting a user-defined message to the main thread.

References  and Samples: