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

后端 未结 2 1317
隐瞒了意图╮
隐瞒了意图╮ 2020-12-16 16:36

Why is it that if I call a seemingly synchronous Windows function like MessageBox() inside of my message loop, the loop itself doesn\'t freeze as if I called

相关标签:
2条回答
  • 2020-12-16 16:56

    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.

    0 讨论(0)
  • 2020-12-16 17:02

    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.

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