Console ReadKey async or callback?

前端 未结 6 841
萌比男神i
萌比男神i 2021-01-04 14:04

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 con

6条回答
  •  一整个雨季
    2021-01-04 14:49

    I didn't find any of the exisiting answers entirely satisfactory so I wrote my own, to work with TAP and .Net 4.5.

    /// 
    /// Obtains the next character or function key pressed by the user
    /// asynchronously. The pressed key is displayed in the console window.
    /// 
    /// 
    /// The cancellation token that can be used to cancel the read.
    /// 
    /// 
    /// The number of milliseconds to wait between polling the
    ///  property.
    /// 
    /// Information describing what key was pressed.
    /// 
    /// Thrown when the read is cancelled by the user input (Ctrl+C etc.)
    /// or when cancellation is signalled via
    /// the passed .
    /// 
    public static async Task 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;
        }
    }
    

提交回复
热议问题