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

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

    // Wait for 'Enter' to be pressed or 5 seconds to elapse
    using (Stream s = Console.OpenStandardInput())
    {
        ManualResetEvent stop_waiting = new ManualResetEvent(false);
        s.BeginRead(new Byte[1], 0, 1, ar => stop_waiting.Set(), null);
    
        // ...do anything else, or simply...
    
        stop_waiting.WaitOne(5000);
        // If desired, other threads could also set 'stop_waiting' 
        // Disposing the stream cancels the async read operation. It can be
        // re-opened if needed.
    }
    

提交回复
热议问题