Shutdown event for console application C#

感情迁移 提交于 2019-12-23 08:53:18

问题


How can i know when my C# console application will be stopping? Is there any event or like that?

Thanks!


回答1:


Use ProcessExit event of the application domain

   class Program
    {
        static void Main(string[] args)
        {
            AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);           


        }

        static void CurrentDomain_ProcessExit(object sender, EventArgs e)
        {
            Console.WriteLine("exit");
        }
    }



回答2:


Handling the event System.Console.CancelKeyPress might help you.

MSDN explains it how to handle this event along with other things that you need to take care of while handling this event, excerpt:

This event is used in conjunction with System.ConsoleCancelEventHandler and System.ConsoleCancelEventArgs. The CancelKeyPress event enables a console application to intercept the CTRL+C signal so the application can decide whether to continue executing or terminate.

Use this event to explicitly control how your application responds to the CTRL+C signal. If your application has simple requirements, you can use the TreatControlCAsInput property instead of this event.

The event handler for this event is executed on a thread pool thread.



来源:https://stackoverflow.com/questions/11291352/shutdown-event-for-console-application-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!