Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call event before Environment.Exit()?

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#?

like image 866
Makah Avatar asked Dec 03 '09 18:12

Makah


2 Answers

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);
    }
}
like image 153
driis Avatar answered Oct 06 '22 21:10

driis


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)
{
}
like image 35
M6rk Avatar answered Oct 06 '22 22:10

M6rk