How to call event before Environment.Exit()?
Asked Answered
K

3

12

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

Krieg answered 3/12, 2009 at 18:53 Comment(0)
F
31

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);
    }
}
Flanigan answered 3/12, 2009 at 19:7 Comment(0)
B
12

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)
{
}
Bilek answered 3/12, 2009 at 19:9 Comment(0)
I
-1

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);
}
Insanity answered 3/12, 2009 at 19:0 Comment(4)
-1: This significantly increases Coupling when there are other easy ways to make things work without this: en.wikipedia.org/wiki/Coupling_(computer_science)Villainage
how would it increase coupling? The question is asking about how to tackle this within a Console application, so calling Environment.Exit would be a valid action. Granted using the events would be easier, but they are going against the AppDomain, not the process.Insanity
If you need to do some cleanup for resource A when it's done being used, keep the cleanup local to A. Don't require A, B, C, and D to make special accomodations for it.Villainage
One case where this may not make the cut is in case of unhandled exceptions which can lead to application exit, in which case MyExit wont be called. Still a valid answer. Dont think this deserve a downvoteBifocals

© 2022 - 2024 — McMap. All rights reserved.