开发者

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?


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
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜