首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Console ReadKey async还是callback?

Console ReadKey async还是callback?
EN

Stack Overflow用户
提问于 2010-08-01 22:41:25
回答 6查看 9.3K关注 0票数 14

我正试着在控制台窗口中按Q退出。我不喜欢我现在的实现。有没有办法可以通过异步或者回调从控制台获取密钥?

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2010-08-01 22:49:20

您可以从另一个线程调用Console.ReadKey(),这样它就不会阻塞您的主线程。(您可以使用.Net 4 Task或旧的Thread启动新线程。)

代码语言:javascript
复制
class Program
{
    static volatile bool exit = false;

    static void Main()
    {
        Task.Factory.StartNew(() =>
            {
                while (Console.ReadKey().Key != ConsoleKey.Q) ;
                exit = true;
            });

        while (!exit)
        {
            // Do stuff
        }
    }
}
票数 21
EN

Stack Overflow用户

发布于 2014-05-13 18:02:14

我没有发现任何现有的答案是完全令人满意的,所以我写了我自己的,使用TAP和.Net 4.5。

代码语言:javascript
复制
/// <summary>
/// Obtains the next character or function key pressed by the user
/// asynchronously. The pressed key is displayed in the console window.
/// </summary>
/// <param name="cancellationToken">
/// The cancellation token that can be used to cancel the read.
/// </param>
/// <param name="responsiveness">
/// The number of milliseconds to wait between polling the
/// <see cref="Console.KeyAvailable"/> property.
/// </param>
/// <returns>Information describing what key was pressed.</returns>
/// <exception cref="TaskCanceledException">
/// Thrown when the read is cancelled by the user input (Ctrl+C etc.)
/// or when cancellation is signalled via
/// the passed <paramred name="cancellationToken"/>.
/// </exception>
public static async Task<ConsoleKeyInfo> ReadKeyAsync(
    CancellationToken cancellationToken,
    int responsiveness = 100)
{
    var cancelPressed = false;
    var cancelWatcher = new ConsoleCancelEventHandler(
        (sender, args) => { cancelPressed = true; });
    Console.CancelKeyPress += cancelWatcher;
    try
    {
        while (!cancelPressed && !cancellationToken.IsCancellationRequested)
        {
            if (Console.KeyAvailable)
            {
                return Console.ReadKey();
            }

            await Task.Delay(
                responsiveness,
                cancellationToken);
        }

        if (cancelPressed)
        {
            throw new TaskCanceledException(
                "Readkey canceled by user input.");
        }

        throw new TaskCanceledException();
    }
    finally
    {
        Console.CancelKeyPress -= cancelWatcher;
    }
}
票数 8
EN

Stack Overflow用户

发布于 2018-06-25 17:39:48

下面是我是如何做到的:

代码语言:javascript
复制
// 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;
    }
}
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3382409

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档