Waiting for keyboard event in console app
Is there a way to get Task
that exits and returns a keypress without a dedicated thread?
// Kernel callback, not a new thread in my process waiting for a keyboard event
var key = await KeyPress();
Because it Console.ReadKey()
is a blocking call and only uses the thread to wait for user input.
source to share
it is that a thread dedicated only to waiting for user input sounds like a waste (not necessarily big, but it looks like it should have an implementation to do this).
I would not bother with this for a console application that expects user input.
If anything, you may be able to achieve what you need using some basic Win32 APIs. The docs for ReadConsoleInput
say:
A process can specify a handle to a console input buffer in one of the function's expectation to determine when there is unread console input. ... the input buffer is not empty, the state of the console input buffer descriptor is signaled. To determine the number of unread input records in the console input buffer, use the
GetNumberOfConsoleInputEvents
function. To read input records from the console input buffer without affecting the number of unread records, use thePeekConsoleInput
function. To discard all unread entries in the console input buffer, use the functionFlushConsoleInputBuffer
.
So, in theory, you could use the descriptor returned GetStdHandle
and pass it in
RegisterWaitForSingleObject
. Then you can convert it to pending task using TaskCompletionSource
eg. as described here .
I have not tested this in practice. This won't block the thread, but IMO, again, the game isn't worth the candle.
source to share