How to call event before Environment.Exit()?

馋奶兔 提交于 2019-12-10 12:48:20

问题


I have a console application in C#. If something goes wrong, I call Environment.Exit() to close my application. I need to disconnect from the server and close some files before the application ends.

In Java, I can implement a shutdown hook and register it via Runtime.getRuntime().addShutdownHook(). How can I achieve the same in C#?


回答1:


You can attach an event handler to the current application domain's ProcessExit event:

using System;
class Program
{
    static void Main(string[] args)
    {
        AppDomain.CurrentDomain.ProcessExit += (s, e) => Console.WriteLine("Process exiting");
        Environment.Exit(0);
    }
}



回答2:


Hook AppDomain events:

private static void Main(string[] args)
{
    var domain = AppDomain.CurrentDomain;
    domain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);
    domain.ProcessExit += new EventHandler(domain_ProcessExit);
    domain.DomainUnload += new EventHandler(domain_DomainUnload);
}
static void MyHandler(object sender, UnhandledExceptionEventArgs args)
{
    Exception e = (Exception)args.ExceptionObject;
    Console.WriteLine("MyHandler caught: " + e.Message);
}

static void domain_ProcessExit(object sender, EventArgs e)
{
}
static void domain_DomainUnload(object sender, EventArgs e)
{
}



回答3:


I'd recommend wrapping the call to Environment.Exit() in your own method and using that throughout. Something like this:

internal static void MyExit(int exitCode){
    // disconnect from network streams
    // ensure file connections are disposed
    // etc.
    Environment.Exit(exitCode);
}


来源:https://stackoverflow.com/questions/1842077/how-to-call-event-before-environment-exit

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