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?
I can't comment on Gulzar's post unfortunately, but here's a fuller example:
Simple threading example to solve this
or a static string up top for getting an entire line.
Here is a solution that uses
Console.KeyAvailable
. These are blocking calls, but it should be fairly trivial to call them asynchronously via the TPL if desired. I used the standard cancellation mechanisms to make it easy to wire in with the Task Asynchronous Pattern and all that good stuff.There are some disadvantages with this.
ReadLine
provides (up/down arrow scrolling, etc.).Im my case this work fine:
A simple example using
Console.KeyAvailable
:Please don't hate me for adding another solution to the plethora of existing answers! This works for Console.ReadKey(), but could easily be modified to work with ReadLine(), etc.
As the "Console.Read" methods are blocking, it's necessary to "nudge" the StdIn stream to cancel the read.
Calling syntax:
Code: