Console ReadKey async or callback?

Viewed 10433

I am trying to do a press Q to quit thing in the console window. I dont like my current implementation. Is there a way i can async or use a callback to get keys from the console?

7 Answers

Here is how I made it:

// Comments language: pt-BR
// Aguarda key no console
private static async Task<ConsoleKey> WaitConsoleKey ( ) {
    try {
        // Prepara retorno
        ConsoleKey key = default;
        // Aguarda uma tecla ser pressionada
        await Task.Run ( ( ) => key = Console.ReadKey ( true ).Key );
        // Retorna a tecla
        return key;
    }
    catch ( Exception ex ) {
        throw ex;
    }
}

This is a non-blocking solution using asynchronous code and cancellation tokens. This method works well when you have some heavy tasks running but want the app to quit responsively when a key is pressed.

// Set up the asynchronous key reader, but don't block.
_ = WaitForKey(cancellationTokenSource);

try
{
    for(;;)
    {
        // Code running in an infinite loop
        await MyTaskAsync(cancellationTokenSource.Token);
    }
}
catch(TaskCanceledException)
{
    // When a key is pressed, we'll end up here
}
finally
{
    // Clean up
}   

async Task WaitForKey(CancellationTokenSource cancellationTokenSource)
{
    // You could filter on a specific character or key combination in this method, such as the OP's 'q' character
    await ReadKeyAsync();
    cancellationTokenSource.Cancel();
}

async Task<ConsoleKeyInfo> ReadKeyAsync(bool intercept = true) => await Task.Run(() => Console.ReadKey(intercept));
Related