简体   繁体   English

Windows消息循环中的sleep()?

[英]Sleep() in windows message loop?

Does a Sleep(sometime) serve a purpose in the typical infinite window message loop, or is it just useless or even harmful? Sleep(sometime)是否在典型的无限窗口消息循环中达到目的,还是只是无用甚至有害?

Some examples contain the Sleep , most of them do not. 一些示例包含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
    }

That call is pointless. 那个电话毫无意义。 GetMessage waits until there's a message in the queue,and while it does, your program will not be taking up CPU. GetMessage会一直等到队列中有消息为止,而同时,该消息不会占用CPU。 There's no need to try to do what it already does. 无需尝试做已经做的事情。

Now about being harmful, maybe ( very likely) it will! 现在关于有害,也许( 很有可能)会! If there are 1000 messages in the queue, it's going to sleep for 500 seconds before it can process them all. 如果队列中有1000条消息,它将休眠500秒,然后才能处理所有消息。 In that time, you'll have accumulated much more than 1000 messages. 到那时,您将积累超过1000条消息。 It won't be long before your window becomes completely useless. 不久之后,您的窗口将完全无用。 Windows do get a lot of messages. Windows确实收到很多消息。 You're going to tell me that you'll wait half a second to respond each time the mouse moves at all over your window? 您要告诉我,每次鼠标窗口上移动 ,您都将等待半秒钟做出响应?

Also, from the documentation , GetMessage will return -1 if there's an error. 此外,如果有错误, GetMessage将从文档中返回-1。 Since -1 is not 0, your loop will try to process the message anyway. 由于-1不为0,因此循环仍将尝试处理该消息。 The more correct way would be to either put in a handler, or exit altogether: 更正确的方法是放入处理程序或完全退出:

while (GetMessage (&msg, NULL, 0, 0) > 0)

The Sleep() call is both completely useless and harmful. Sleep()调用完全无用且有害。 GetMessage() will already sleep your thread until there is a message ready for one of your windows. GetMessage()将已经使您的线程休眠,直到其中一个窗口准备好一条消息为止。 Adding the Sleep(500) will just make your windows unresponsive because they will only process two messages a second. 添加Sleep(500)只会使您的窗口无响应,因为它们每秒仅处理两条消息。

Windows works when your app doesn't. Windows在您的应用无法运行时起作用。 You do not even need to get technical about this: The example code you posted is the equivalent of a customer service rep sleeping on the job when the phone is ringing off the hook. 您甚至不需要获得有关此方面的技术知识:发布的示例代码等效于电话响起时正在工作的客户服务代表。 Remove Sleep() . 删除Sleep()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM