Sleep() - "Do not disturb"!

mjcoon

Well-Known Member
Licensed User
In a trivial experimental app I have a loop including a Sleep(1000). The loop is effectively infinite, but I expected to be able to click the (sole) button on Form1 to terminate the program.

But I found that the Sleep() (and the rest of the loop, which just makes a sound) is effectively non-interruptible, and I had to include a DoEvents in the loop before I could break in.

I found this mildly surprising. Is there no way to have a pause that can be interrupted?

Mike.
 

agraham

Expert
Licensed User
Longtime User
I found this mildly surprising.
Without the DoEvents call Sleeping in a loop doesn't let the program get back to its' message loop to process the messages that might then set a flag or by some other way break out of the loop. DoEvents calls the applications' message loop and processes any message waiting. Without DoEvents you are stuck in the loop. Looping is not a good idea in an event driven environment, there are usually other ways to deal with such a requirement.
 

mjcoon

Well-Known Member
Licensed User
... Looping is not a good idea in an event driven environment, there are usually other ways to deal with such a requirement.

Looping is of the essence in many programs, else there would not be so many ways of constructing loops in every programming language!

But to be less silly, this was just a test program to generate noise to allow me to arrange cradle audio. So the complexity of setting up a timer (especially since I wanted the delay after the first action, not before) was not really warranted.

My surprise was merely that a keyword whose purpose is to cause the program to delay/suspend for a period does not include DoEvents functionality already. If the Help for Sleep() had said this was the case I would not have fallen into even this tiny trap. It's the Sleep() that is the trap, not the loop!

Mike.
 
Top