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.

+3


source to share


2 answers


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 the PeekConsoleInput

function. To discard all unread entries in the console input buffer, use the function FlushConsoleInputBuffer

.

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.

0


source


You can open standard input, which has asynchronous read operations:



using (var stream = Console.OpenStandardInput())
{
    var buffer = new byte[1];
    var bytesRead = await stream.ReadAsync(buffer, 0, 1);
    char c = (char)buffer[0];
    Console.WriteLine(c);
}

      

0


source







All Articles