Console ReadKey async or callback?

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

    You can call Console.ReadKey() from another thread, so that it doesn't block your main thread. (You can use the .Net 4 Task or the old Thread to start the new 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
            }
        }
    }
    

提交回复
热议问题