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

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

    string ReadLine(int timeoutms)
    {
        ReadLineDelegate d = Console.ReadLine;
        IAsyncResult result = d.BeginInvoke(null, null);
        result.AsyncWaitHandle.WaitOne(timeoutms);//timeout e.g. 15000 for 15 secs
        if (result.IsCompleted)
        {
            string resultstr = d.EndInvoke(result);
            Console.WriteLine("Read: " + resultstr);
            return resultstr;
        }
        else
        {
            Console.WriteLine("Timed out!");
            throw new TimedoutException("Timed Out!");
        }
    }
    
    delegate string ReadLineDelegate();
    

提交回复
热议问题