Console ReadKey async or callback?

前端 未结 6 878
萌比男神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:41

    Taking from all the answers here, this is my version:

    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();
    }
    
    • It doesn't require Main to do anything in a loop, allowing it to simply orchestrate between handling keys and manipulating properties of the worker class.
    • Taking the hint from @Hans, the KeyHandler doesn't need to async up a new thread since Console.ReadKey blocks until a key is received.

提交回复
热议问题