How to add a Timeout to Console.ReadLine()?

后端 未结 30 2593
耶瑟儿~
耶瑟儿~ 2020-11-22 04:57

I have a console app in which I want to give the user x seconds to respond to the prompt. If no input is made after a certain period of time, program logic should

30条回答
  •  死守一世寂寞
    2020-11-22 05:53

    This worked for me.

    ConsoleKeyInfo k = new ConsoleKeyInfo();
    Console.WriteLine("Press any key in the next 5 seconds.");
    for (int cnt = 5; cnt > 0; cnt--)
      {
        if (Console.KeyAvailable)
          {
            k = Console.ReadKey();
            break;
          }
        else
         {
           Console.WriteLine(cnt.ToString());
           System.Threading.Thread.Sleep(1000);
         }
     }
    Console.WriteLine("The key pressed was " + k.Key);
    

提交回复
热议问题