سؤال

Does a Sleep(sometime) serve a purpose in the typical infinite window message loop, or is it just useless or even harmful?

Some examples contain the Sleep, most of them do not.

    // 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. 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. In that time, you'll have accumulated much more than 1000 messages. It won't be long before your window becomes completely useless. Windows do get a lot of messages. 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. Since -1 is not 0, your loop will try to process the message anyway. 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. GetMessage() will already sleep your thread until there is a message ready for one of your windows. Adding the Sleep(500) will just make your windows unresponsive because they will only process two messages a second.

Windows works when your app doesn't. 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().

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top