How can I continue to run my console application until a key press (like Esc is pressed?)
I'm assuming its wrapped around a while loop. I don't like ReadKey
as it blocks operation and asks for a key, rather than just continue and listen for the key press.
How can this be done?
According to my experience, in console apps the easiest way to read the last key pressed is as follows (Example with arrow keys):
I use to avoid loops, instead I write the code above within a method, and I call it at the end of both "Method1" and "Method2", so, after executing "Method1" or "Method2", Console.ReadKey().Key is ready to read the keys again.
The shortest way:
Console.ReadKey()
is a blocking function, it stops the execution of the program and waits for a key press, but thanks to checkingConsole.KeyAvailable
first, thewhile
loop is not blocked, but running until the Esc is pressed.From the video curse Building .NET Console Applications in C# by Jason Roberts at http://www.pluralsight.com
We could do following to have multiple running process
Addressing cases that some of the other answers don't handle well:
Many of the solutions on this page involve polling
Console.KeyAvailable
or blocking onConsole.ReadKey
. While it's true that the .NETConsole
is not very cooperative here, you can useTask.Run
to move towards a more modernAsync
mode of listening.The main issue to be aware of is that, by default, your console thread isn't set up for
Async
operation--meaning that, when you fall out of the bottom of yourmain
function, instead of awaitingAsync
completions, your AppDoman and process will end. A proper way to address this would be to use Stephen Cleary's AsyncContext to establish fullAsync
support in your single-threaded console program. But for simpler cases, like waiting for a keypress, installing a full trampoline may be overkill.The example below would be for a console program used in some kind of iterative batch file. In this case, when the program is done with its work, normally it should exit without requiring a keypress, and then we allow an optional key press to prevent the app from exiting. We can pause the cycle to examine things, possibly resuming, or use the pause as a known 'control point' at which to cleanly break out of the batch file.
You can change your approach slightly - use
Console.ReadKey()
to stop your app, but do your work in a background thread:In the
myWorker.DoStuff()
function you would then invoke another function on a background thread (usingAction<>()
orFunc<>()
is an easy way to do it), then immediately return.with below code you can listen SpaceBar pressing , in middle of your console execution and pause until another key is pressed and also listen for EscapeKey for breaking the main loop