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 continue. We assume a timeout means empty response.
What is the most straightforward way of approaching this?
Best Solution
I'm surprised to learn that after 5 years, all of the answers still suffer from one or more of the following problems:
I believe my solution will solve the original problem without suffering from any of the above problems:
Calling is, of course, very easy:
Alternatively, you can use the
TryXX(out)
convention, as shmueli suggested:Which is called as follows:
In both cases, you cannot mix calls to
Reader
with normalConsole.ReadLine
calls: if theReader
times out, there will be a hangingReadLine
call. Instead, if you want to have a normal (non-timed)ReadLine
call, just use theReader
and omit the timeout, so that it defaults to an infinite timeout.So how about those problems of the other solutions I mentioned?
The only problem that I foresee with this solution is that it is not thread-safe. However, multiple threads can't really ask the user for input at the same time, so synchronization should be happening before making a call to
Reader.ReadLine
anyway.