2

[Console Application]

I would like to have one method on a timer, (Thread.Sleep) and run another method along side it, waiting for the user's response. If the timer runs out before the user can respond (ReadKey), then they will lose a life.

How can I, in short, have a ReadKey be on a timer?

Ian Cordle
  • 206
  • 4
  • 13

2 Answers2

5

Console.ReadKey() is blocking so you can't use that.

You can loop using Console.KeyAvailable() and Thread.Sleep(). No Timer necessary.

var lastKeyTime = DateTime.Now;
...
while (true)
{
   if (Console.KeyAvailable())
   {
      lastKeyTime = DateTime.Now;
      // Read and process key
   }
   else
   {
      if (DateTime.Now - lastKeyTime  > timeoutSpan)
      {
         lastKeyTime = DateTime.Now;
         // lose a live
      }
   }
   Thread.Sleep(50);  // from 1..500 will work
}
H H
  • 263,252
  • 30
  • 330
  • 514
  • If you go down this route (and need any sort of accurate timing), make sure to keep track of actual time since the countdown started rather than relying on multiples of the sleep interval. – SoftMemes Jul 11 '11 at 20:59
  • You can sleep for short periods but use DateTime.Now's milliseconds (subtracting the original value you saved before entering the loop) to see the total elapsed time. – Ed Bayiates Jul 11 '11 at 21:04
  • Okay, this got me on the right track, I think I have an idea that is a tad simpler than your example. Thanks for your help. – Ian Cordle Jul 12 '11 at 01:43
0

You can create a shared ManualResetEvent, start up a new thread (or use the thread pool) and use the .WaitOne() method with a timeout on the second thread. After ReadKey() returns, you signal the event, the other thread will know if it has been woken up because of a key having been pressed or because of the timeout and can react accordingly.

SoftMemes
  • 5,602
  • 4
  • 32
  • 61
  • 1
    The point is that `ReadKey()` _doesn't_ return when a timeout happens. – H H Jul 11 '11 at 21:03
  • @Henk, indeed - but the program logic can still continue on the other thread. Is it a problem that ReadKey() hasn't returned yet, or will lanVal still want to read keys..? – SoftMemes Jul 11 '11 at 21:06