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

后端 未结 30 2576
耶瑟儿~
耶瑟儿~ 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 06:00

    Will this approach using Console.KeyAvailable help?

    class Sample 
    {
        public static void Main() 
        {
        ConsoleKeyInfo cki = new ConsoleKeyInfo();
    
        do {
            Console.WriteLine("\nPress a key to display; press the 'x' key to quit.");
    
    // Your code could perform some useful task in the following loop. However, 
    // for the sake of this example we'll merely pause for a quarter second.
    
            while (Console.KeyAvailable == false)
                Thread.Sleep(250); // Loop until input is entered.
            cki = Console.ReadKey(true);
            Console.WriteLine("You pressed the '{0}' key.", cki.Key);
            } while(cki.Key != ConsoleKey.X);
        }
    }
    

提交回复
热议问题