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.
Edit —- Possible Idea…
DateTime timeAtStart = DateTime.Now;
int maxWaitTime = 15000;
while (true)
{
if (GetAsyncKeyState(System.Windows.Forms.Keys.Escape) != 0)
{
break;
}
if ((DateTime.Now - timeAtStart).TotalMilliseconds >= maxWaitTime)
{
break;
}
}
This doesn’t use any sort of timer but looks like it could work, any suggestions?
Edit 2: The above works for me and now allows me to break the wait when escape is pressed. I have noticed the delay is more accurate than using Thread.Sleep too!
First sample is using Timer, ManuelResetEvent and Global Keyboard hook:
I did not include keyboard hook code because it’s too large. You can find it here.
When you hook to keyboard and ESC is pressed, simply call: _signal.Set(). This first sample is just to give you an idea.
Second sample:
EDITED:
First sample is more reliable as keyboard hook use callback to inform which key was pressed. Second sample works like ‘Pull’ and it can happen not every key press will be collected.