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

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

    This is a fuller example of Glen Slayden's solution. I happended to make this when building a test case for another problem. It uses asynchronous I/O and a manual reset event.

    public static void Main() {
        bool readInProgress = false;
        System.IAsyncResult result = null;
        var stop_waiting = new System.Threading.ManualResetEvent(false);
        byte[] buffer = new byte[256];
        var s = System.Console.OpenStandardInput();
        while (true) {
            if (!readInProgress) {
                readInProgress = true;
                result = s.BeginRead(buffer, 0, buffer.Length
                  , ar => stop_waiting.Set(), null);
    
            }
            bool signaled = true;
            if (!result.IsCompleted) {
                stop_waiting.Reset();
                signaled = stop_waiting.WaitOne(5000);
            }
            else {
                signaled = true;
            }
            if (signaled) {
                readInProgress = false;
                int numBytes = s.EndRead(result);
                string text = System.Text.Encoding.UTF8.GetString(buffer
                  , 0, numBytes);
                System.Console.Out.Write(string.Format(
                  "Thank you for typing: {0}", text));
            }
            else {
                System.Console.Out.WriteLine("oy, type something!");
            }
        }
    

提交回复
热议问题