66

I have a little console C# program like

Class Program 
{ 
    static void main(string args[]) 
    {
    }
}

Now I want to do something after main() exit. I tried to write a deconstructor for Class Program, but it never get hit.

Does anybody know how to do it.

Thanks a lot

Frank
  • 7,235
  • 9
  • 46
  • 56

1 Answers1

139

Try the ProcessExit event of AppDomain:

using System;
class Test {
    static void Main(string[] args)
    {
        AppDomain.CurrentDomain.ProcessExit += new EventHandler (OnProcessExit); 
        // Do something here
    }

    static void OnProcessExit (object sender, EventArgs e)
    {
        Console.WriteLine ("I'm out of here");
    }
}
Gonzalo
  • 20,805
  • 3
  • 75
  • 78
  • 3
    My answer was incorrect, this is the best approach. – ace Mar 31 '10 at 18:27
  • This is the most generic solution, but be careful here, as the `ProcessExit` event is time-limited to three seconds (like finalizers are when the application shuts down). http://msdn.microsoft.com/en-us/library/system.appdomain.processexit.aspx – Adam Robinson Mar 31 '10 at 18:28
  • Thanks, it works... First time, then it stopped working! :-( – gatopeich Aug 13 '12 at 15:14
  • will this work even if the user closes the program? – NSjonas Nov 15 '12 at 18:24
  • 5
    AppDomain.ProcessExit is not guaranteed to be calledhttp://blogs.msdn.com/b/jmstall/archive/2006/11/26/process-exit-event.aspx – Barka Feb 24 '13 at 06:47
  • 7
    Sure, 'rudely' killing the process will not give a chance to execute ProcessExit. Hence the 'rudely' :-) – Gonzalo Feb 25 '13 at 05:44
  • 4
    Hitting the X button at the top-right corner of a window can 'rudely' kill the process, for anyone unaware. – Miryafa Jun 30 '17 at 21:22
  • 10
    i.e. this answer is entirely useless in a large number of cases. – j riv Jun 14 '18 at 18:41
  • Miryafa, this works when we hit the X button at the top right corner of the application. I am using a WPF application and its working for me. Yet to check with a console though. – Renjith Jul 22 '18 at 02:32
  • 2
    This also will not work if the application throws an exception. – Andrey Belenkiy Jan 14 '20 at 11:43
  • This does not work for me in a console application. I'm using .NET 4.7.2 – im2rnado Jul 08 '21 at 12:01