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?
Much more contemporary and Task based code would look something like this:
This worked for me.
I had a unique situation of having a Windows Application (Windows Service). When running the program interactively
Environment.IsInteractive
(VS Debugger or from cmd.exe), I used AttachConsole/AllocConsole to get my stdin/stdout. To keep the process from ending while the work was being done, the UI Thread callsConsole.ReadKey(false)
. I wanted to cancel the waiting the UI thread was doing from another thread, so I came up with a modification to the solution by @JSquaredD.This seems to be the simplest, working solution, that doesn't use any native APIs:
Example usage:
Example implementation of Eric's post above. This particular example was used to read information that was passed to a console app via pipe: