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

后端 未结 30 3078
耶瑟儿~
耶瑟儿~ 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:49

    I came to this answer and end up doing:

        /// 
        /// Reads Line from console with timeout. 
        /// 
        /// If user does not enter line in the specified time.
        /// Time to wait in milliseconds. Negative value will wait forever.        
        ///         
        public static string ReadLine(int timeout = -1)
        {
            ConsoleKeyInfo cki = new ConsoleKeyInfo();
            StringBuilder sb = new StringBuilder();
    
            // if user does not want to spesify a timeout
            if (timeout < 0)
                return Console.ReadLine();
    
            int counter = 0;
    
            while (true)
            {
                while (Console.KeyAvailable == false)
                {
                    counter++;
                    Thread.Sleep(1);
                    if (counter > timeout)
                        throw new System.TimeoutException("Line was not entered in timeout specified");
                }
    
                cki = Console.ReadKey(false);
    
                if (cki.Key == ConsoleKey.Enter)
                {
                    Console.WriteLine();
                    return sb.ToString();
                }
                else
                    sb.Append(cki.KeyChar);                
            }            
        }
    

提交回复
热议问题