How to call event before Environment.Exit()?

Makah picture Makah · Dec 3, 2009 · Viewed 11k times · Source

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

Answer

driis picture driis · Dec 3, 2009

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