How to delay program for a certain number of milliseconds, or until a key is pressed?

Posted by Jack on Stack Overflow See other posts from Stack Overflow or by Jack
Published on 2011-01-16T13:12:46Z Indexed on 2011/01/16 13:53 UTC
Read the original article Hit count: 136

Filed under:
|
|

I need to delay my program's execution for a specified number of milliseconds, but also want the user to be able to escape the wait when a key is pressed. If no key is pressed the program should wait for the specified number of milliseconds.

I have been using Thread.Sleep to halt the program (which in the context of my program I think is ok as the UI is set to minimise during the execution of the main method).

I have thought about doing something like this:

while(GetAsyncKeyState(System.Windows.Forms.Keys.Escape) == 0 || waitTime > totalWait)
{
    Thread.Sleep(100);
    waitTime += 100;
}

As Thread.Sleep will wait until at least the time specified before waking the thread up, there will obviously be a large unwanted extra delay as it is scaled up in the while loop.

Is there some sort of method that will sleep for a specified amount of time but only while a condition holds true? Or is the above example above the "correct" way to do it but to use a more accurate Sleep method? If so what method can I use?

Thanks in advance for your help.

© Stack Overflow or respective owner

Related posts about c#

Related posts about sleep