Capture console exit C#

前端 未结 10 2063
悲&欢浪女
悲&欢浪女 2020-11-22 04:01

I have a console application that contains quite a lot of threads. There are threads that monitor certain conditions and terminate the program if they are true. This termi

10条回答
  •  星月不相逢
    2020-11-22 04:38

    I've had a similar problem, just my console App would be running in infinite loop with one preemptive statement on middle. Here is my solution:

    class Program
    {
        static int Main(string[] args)
        {
            // Init Code...
            Console.CancelKeyPress += Console_CancelKeyPress;  // Register the function to cancel event
    
            // I do my stuffs
    
            while ( true )
            {
                // Code ....
                SomePreemptiveCall();  // The loop stucks here wating function to return
                // Code ...
            }
            return 0;  // Never comes here, but...
        }
    
        static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
        {
            Console.WriteLine("Exiting");
            // Termitate what I have to terminate
            Environment.Exit(-1);
        }
    }
    

提交回复
热议问题