views:

121

answers:

3

I have a console application. If something goes wrong i need to call Environment.Exit(); to close my app. I need to disconnect and close some files before my application exit.

In Java i can implement Runtime.getRuntime().addShutdownHook(). Can someone help me?

A: 

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);
}
Agent_9191
does not exist in C # an exit event?
Makah
-1: This significantly increases Coupling when there are other *easy* ways to make things work without this: http://en.wikipedia.org/wiki/Coupling_(computer_science)
280Z28
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.
Agent_9191
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.
280Z28
+3  A: 

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);
    }
}
driis
I dont like lambda :). But thanks, ill try.
Makah
+4  A: 

Hook AppDomain events: http://msdn.microsoft.com/en-us/library/system.appdomain.aspx

Example:

      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)
         {
         }
M6rk