只要还没有触发CancelKeyPress事件,保持控制台应用程序打开的最佳方法是什么?
我宁愿不使用Console.Read或Console.ReadLine,因为我不想接受输入.我只是想让底层应用程序在触发时打印到控制台事件详细信息.然后一旦解雇了CancelKeyPress事件,我想优雅地关闭应用程序.
我假设"优雅地关闭应用程序"是你在这里努力的部分.否则,您的应用程序将自动退出ctrl-c.你应该改变标题.
这是我认为你需要的快速演示.使用锁定和监视器进行通知可以进一步细化.我不确定你到底需要什么,所以我只是假装...
class Program { private static volatile bool _s_stop = false; public static void Main(string[] args) { Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress); while (!_s_stop) { /* put real logic here */ Console.WriteLine("still running at {0}", DateTime.Now); Thread.Sleep(3000); } Console.WriteLine("Graceful shut down code here..."); //don't leave this... demonstration purposes only... Console.ReadLine(); } static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e) { //you have 2 options here, leave e.Cancel set to false and just handle any //graceful shutdown that you can while in here, or set a flag to notify the other //thread at the next check that it's to shut down. I'll do the 2nd option e.Cancel = true; _s_stop = true; Console.WriteLine("CancelKeyPress fired..."); } }
_s_stop布尔值应声明为volatile或过于雄心勃勃的优化器可能导致程序无限循环.
该_s_stop
布尔应声明示例代码挥发,或过于雄心勃勃的优化可能会导致程序无限循环.