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?

3
  • 1
    Similar question stackoverflow.com/questions/57615/… Commented Jul 11, 2011 at 20:53
  • ... or C# 5.0 CTP - new Async features would be a good fit. Commented Jul 11, 2011 at 20:53
  • @mdm, I don't see how the new async features would help you much here. Commented Jul 11, 2011 at 20:58

2 Answers 2

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 } 
Sign up to request clarification or add additional context in comments.

3 Comments

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.
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.
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.
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.

2 Comments

The point is that ReadKey() doesn't return when a timeout happens.
@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..?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.