Ian Cordle
Ian Cordle

Reputation: 206

C# - How to "Force Quit" a Method

[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?

Upvotes: 2

Views: 481

Answers (2)

Henk Holterman
Henk Holterman

Reputation: 273179

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
}

Upvotes: 5

SoftMemes
SoftMemes

Reputation: 5702

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.

Upvotes: 0

Related Questions