Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for Keypress (or) N Seconds to Expire

Suppose my console program performs multiple lengthy tasks. Between these tasks, I'd like it to pause - either for a few seconds or until any key gets pressed. (Whichever comes first.)

These criteria are easy to check on their own, but they refuse to get along when I try combining them: Either the timing mechanism pauses for a few seconds before ReadKey starts, or Readkey blocks out the thread entirely until satisfied. How can I satisfy both conditions?

like image 454
4444 Avatar asked Aug 02 '12 20:08

4444


2 Answers

One way to do this in C# 4.0:

Task.Factory.StartNew(() => Console.ReadKey()).Wait(TimeSpan.FromSeconds(5.0));
like image 121
lesscode Avatar answered Sep 28 '22 12:09

lesscode


One way to do this is without a timer at all. Create a loop that makes the thread sleep for say 25 milliseconds, and then checks whether a key has been pressed via Console.KeyAvailable (which is non-blocking), or until the time between DateTime.Now() and the time of start of the loop has exceeded the timeout.

like image 39
ikh Avatar answered Sep 28 '22 10:09

ikh