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

后端 未结 30 2918
耶瑟儿~
耶瑟儿~ 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条回答
  •  萌比男神i
    2020-11-22 05:56

    As if there weren't already enough answers here :0), the following encapsulates into a static method @kwl's solution above (the first one).

        public static string ConsoleReadLineWithTimeout(TimeSpan timeout)
        {
            Task task = Task.Factory.StartNew(Console.ReadLine);
    
            string result = Task.WaitAny(new Task[] { task }, timeout) == 0
                ? task.Result 
                : string.Empty;
            return result;
        }
    

    Usage

        static void Main()
        {
            Console.WriteLine("howdy");
            string result = ConsoleReadLineWithTimeout(TimeSpan.FromSeconds(8.5));
            Console.WriteLine("bye");
        }
    

提交回复
热议问题