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?
If you're in the
Main()
method, you can't useawait
, so you'll have to useTask.WaitAny()
:However, C# 7.1 introduces the possiblity to create an async
Main()
method, so it's better to use theTask.WhenAny()
version whenever you have that option:I came to this answer and end up doing:
One way or another you do need a second thread. You could use asynchronous IO to avoid declaring your own:
If the read returns data, set the event and your main thread will continue, otherwise you'll continue after the timeout.
I may be reading too much into the question, but I am assuming the wait would be similar to the boot menu where it waits 15 seconds unless you press a key. You could either use (1) a blocking function or (2) you could use a thread, an event, and a timer. The event would act as a 'continue' and would block until either the timer expired or a key was pressed.
Pseudo-code for (1) would be:
As if there weren't already enough answers here :0), the following encapsulates into a static method @kwl's solution above (the first one).
Usage
I think you will need to make a secondary thread and poll for a key on the console. I know of no built in way to accomplish this.