Windows消息循环中的Sleep()?

Hor*_*ter 1 c++ winapi sleep message-loop

aSleep(sometime)在典型的无限窗口消息循环中是否有用,或者它只是无用甚至有害?

有些示例包含Sleep,但大多数示例不包含。

    // Main message loop:
    MSG msg;
    while (GetMessage(&msg, NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
        Sleep(500); // As pointed out below, completely nonsense
        Sleep(5); // Would have been the better example, but still bad
    }
Run Code Online (Sandbox Code Playgroud)

chr*_*ris 5

这个电话毫无意义。GetMessage等待直到队列中有消息,当消息出现时,你的程序将不会占用CPU。没有必要尝试做它已经做的事情。

现在说到有害,也许(可能)它会!如果队列中有 1000 条消息,它将休眠 500 秒,然后才能处理所有消息。那时,您将积累超过 1000 条消息。用不了多久你的窗户就会变得完全无用。Windows 确实收到了大量消息。您打算告诉我,每次鼠标在窗口上移动时,您都会等待半秒钟来响应?

另外,根据文档GetMessage如果出现错误,将返回 -1。由于 -1 不是 0,因此您的循环无论如何都会尝试处理该消息。更正确的方法是要么放入处理程序,要么完全退出:

while (GetMessage (&msg, NULL, 0, 0) > 0)
Run Code Online (Sandbox Code Playgroud)