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

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

    One way or another you do need a second thread. You could use asynchronous IO to avoid declaring your own:

    • declare a ManualResetEvent, call it "evt"
    • call System.Console.OpenStandardInput to get the input stream. Specify a callback method that will store its data and set evt.
    • call that stream's BeginRead method to start an asynchronous read operation
    • then enter a timed wait on a ManualResetEvent
    • if the wait times out, then cancel the read

    If the read returns data, set the event and your main thread will continue, otherwise you'll continue after the timeout.

提交回复
热议问题