Listen for key press in .NET console app

后端 未结 9 1467
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 05:02

How can I continue to run my console application until a key press (like Esc is pressed?)

I\'m assuming its wrapped around a while loop. I don\'t like

9条回答
  •  深忆病人
    2020-11-22 05:17

    You can change your approach slightly - use Console.ReadKey() to stop your app, but do your work in a background thread:

    static void Main(string[] args)
    {
        var myWorker = new MyWorker();
        myWorker.DoStuff();
        Console.WriteLine("Press any key to stop...");
        Console.ReadKey();
    }
    

    In the myWorker.DoStuff() function you would then invoke another function on a background thread (using Action<>() or Func<>() is an easy way to do it), then immediately return.

提交回复
热议问题