If MessageBox()/related are synchronous, why doesn't my message loop freeze?

戏子无情 提交于 2019-11-29 03:50:44

The MessageBox() and similar Windows API functions are not blocking the execution, like an IO operation or mutexing would do. The MessageBox() function creates a dialog box usually with an OK button - so you'd expect automatic handling of the Windows messages related to the message box. This is implemented with it's own message loop - no new thread is created, but your application remains responsive, because selected messages like Paint are handled calling recursively your WndProc() function, and some messages are not transmitted to, because of the modal type of the created window.

Sleep() and other functions called directly from your WndProc() handling a Windows message, would actually block the execution of your single threaded Message Loop, no other message would be processed.

MessageBox runs its own Win32 message loop (so as not to freeze calling app).

Beware of using it in non reentrant functions...

EDIT: to elaborate: Message loop on windows is something like that (stolen from msdn):

while( (bRet = GetMessage( &msg, NULL, 0, 0 )) != 0)
{ 
    if (bRet == -1)
    {
        // handle the error and possibly exit
    }
    else
    {
        TranslateMessage(&msg); 
        DispatchMessage(&msg); 
    }
} 

DispatchMessage will call whatever window procedure it needs to. That window proc can start its own loop (on the same thread), and it will call DispatchMessage itself, which will call whatever message handlers.

If you want to see it, launch your app in debugger, pop up message box and break. You will be dropped somewhere within its loop. Look at the callstack and see if you can find parent loop.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!