How can I keep a console open until CancelKeyPress event is fired?

前端 未结 5 543
失恋的感觉
失恋的感觉 2021-01-12 00:19

What is the best way to keep a console application open as long as the CancelKeyPress event has not been fired?

I would prefer to not use Console.Read or Console.Rea

相关标签:
5条回答
  • 2021-01-12 00:54

    This may be what you're looking for:

    http://msdn.microsoft.com/en-us/library/system.console.cancelkeypress.aspx

    0 讨论(0)
  • 2021-01-12 00:56

    The _s_stop boolean should be declared volatile in the example code, or an overly-ambitious optimizer might cause the program to loop infinitely.

    0 讨论(0)
  • 2021-01-12 00:59

    Simply run your program or codes without debugging, on your keyboard key in CTRL + f5 instead of F5(debugging).

    0 讨论(0)
  • 2021-01-12 01:01

    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 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...");
        }
    
    }
    

    The _s_stop boolean should be declared volatile or an overly-ambitious optimizer might cause the program to loop infinitely.

    0 讨论(0)
  • 2021-01-12 01:06

    There is already a handler bound to CancelKeyPress that terminates your application, the only reason to hook to it is if you want to intercept the event and prevent the app from closing.

    In your situation, just put your app into an infinite loop, and let the built in event handler kill it. You may want to look into using something like Wait(1) or a background process to prevent it from using tons of CPU while doing nothing.

    0 讨论(0)
提交回复
热议问题