Console ReadKey async还是回调?

时间:2010-08-01 14:41:25

标签: .net

我正在尝试按Q来退出控制台窗口中的内容。我不喜欢我目前的实施。有没有办法可以异步或使用回调从控制台获取密钥?

6 个答案:

答案 0 :(得分:15)

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

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
        }
    }
}

答案 1 :(得分:5)

您可以使用KeyAvailable属性(Framework 2.0):

if (System.Console.KeyAvailable)
{
   ConsoleKeyInfo key = System.Console.ReadKey(true);//true don't print char on console
   if (key.Key == ConsoleKey.Q)
   {
       //Do something
   }
}

答案 2 :(得分:5)

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

/// <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;
    }
}

答案 3 :(得分:0)

从这里得到的所有答案,这是我的版本:

public class KeyHandler
{
    public event EventHandler KeyEvent;

    public void WaitForExit()
    {
        bool exit = false;
        do
        {
            var key = Console.ReadKey(true); //blocks until key event
            switch (key.Key)
            {
                case ConsoleKey.Q:
                    exit = true;
                    break;
               case ConsoleKey.T:
                    // raise a custom event eg: Increase throttle
                    break;
            }
        }
        while (!exit);
    }
}


static void Main(string[] args)
{
    var worker = new MyEventDrivenClassThatDoesCoolStuffByItself();
    worker.Start();

    var keyHandler = new KeyHandler();
    keyHandler.KeyEvent+= keyHandler_KeyEvent; // modify properties of your worker
    keyHandler.WaitForExit();
}
  • 它不需要Main在循环中执行任何操作,只允许它在处理键和操作worker类的属性之间进行简单编排。
  • 从@Hans中获取提示,KeyHandler不需要异步启动新线程,因为Console.ReadKey会阻塞,直到收到密钥为止。

答案 4 :(得分:0)

这是我使用KeyAvailable创建的实现。这会在控制台窗口的底部保持提示,而所有内容都打印在&#34;到控制台从顶部开始。

public class Program
{
    private static int consoleLine;
    private static int consolePromptLine;
    private static bool exit;
    static string clearLine = new string(' ', Console.BufferWidth - 1);

    public static void Main(string[] args)
    {
        StringBuilder commandCapture = new StringBuilder(10);
        string promptArea = "Command> ";

        consolePromptLine = Console.WindowTop + Console.WindowHeight - 1;

        ClearLine(consolePromptLine);
        Console.Write(promptArea);

        while (!exit)
        {
            // Do other stuff

            // Process input
            if (Console.KeyAvailable)
            {
                var character = Console.ReadKey(true);

                if (character.Key == ConsoleKey.Enter)
                {
                    if (commandCapture.Length != 0)
                    {
                        ProcessCommand(commandCapture.ToString());
                        commandCapture.Clear();
                        ClearLine(consolePromptLine);
                        Console.Write(promptArea);
                    }
                }
                else
                {
                    if (character.Key == ConsoleKey.Backspace)
                    {
                        if (commandCapture.Length != 0)
                        {
                            commandCapture.Remove(commandCapture.Length - 1, 1);
                            ClearLine(consolePromptLine);
                            Console.Write(promptArea);
                            Console.Write(commandCapture.ToString());
                        }
                    }
                    else
                    {
                        commandCapture.Append(character.KeyChar);
                        Console.SetCursorPosition(0, consolePromptLine);
                        Console.Write(promptArea);
                        Console.Write(commandCapture.ToString());
                    }
                }
            }
        }

    }

    private static void ProcessCommand(string command)
    {
        if (command == "start")
        {
            Task<string> testTask = new Task<string>(() => { System.Threading.Thread.Sleep(4000); return "Test Complete"; });

            testTask.ContinueWith((t) => { Print(t.Result); }, TaskContinuationOptions.ExecuteSynchronously);
            testTask.Start();
        }
        else if (command == "quit")
        {
            exit = true;
        }

        Print(command);
        consolePromptLine = Console.WindowTop + Console.WindowHeight - 1;
    }

    public static void Print(string text)
    {
        ClearLine(consoleLine);
        Console.WriteLine(text);
        consoleLine = Console.CursorTop;
    }

    public static void ClearLine(int line)
    {
        Console.SetCursorPosition(0, line);
        Console.Write(clearLine);
        Console.SetCursorPosition(0, line);
    }
}

答案 5 :(得分:0)

这是我的做法:

// 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;
    }
}