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.
GetMessagewaits 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,
GetMessagewill 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: