我怎样才能保持一个控制台打开,直到CancelKey preSS事件被解雇? [英] How can I keep a console open until CancelKeyPress event is fired?
问题描述
什么是保持一个控制台应用程序,只要CancelKey preSS事件还没有被解雇开的最好方式?
What is the best way to keep a console application open as long as the CancelKeyPress event has not been fired?
我会preFER不使用Console.Read或到Console.ReadLine,因为我不想接受输入。我只想让底层应用程序打印到控制台事件的详细信息,因为他们被解雇。那么一旦CancelKey preSS事件触发我想平稳地关闭应用程序。
I would prefer to not use Console.Read or Console.ReadLine as I do not want to accept input. I just want to enable the underlying application to print to the console event details as they are fired. Then once the CancelKeyPress event is fired I want to gracefully shut down the application.
推荐答案
我假设正常关闭的应用程序是你在挣扎这里的一部分。否则,你的应用程序会自动退出的CTRL-C。您应该更改标题。
I'm assuming that "gracefully shut down the application" is the part you are struggling with here. Otherwise your application will automatically exit on ctrl-c. You should change the title.
下面是什么,我想你需要一个快速演示。它可以改进多一点与使用锁定和监控的通知。我不知道正是你需要的,所以我就提出这个...
Here's a quick demo of what I think you need. It could be refined a bit more with use of locking and Monitors for notification. I'm not sure exactly what you need though, so I'll just pose this...
class Program
{
private static 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...");
}
}
这篇关于我怎样才能保持一个控制台打开,直到CancelKey preSS事件被解雇?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!