tags:

views:

292

answers:

2

Hi all,

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

+8  A: 

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
This works even better.
Roberto Sebestyen
My answer was incorrect, this is the best approach.
ace
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
+1  A: 

Best way is to just use a finally clause:

class Program 
{ 
    static void Main(string args[]) 
    {
        try {
            // your code...
        } finally {
            // code to run when application finishes
        }
    }
}

Another option is to bind to the ApplicationExit event:

class Program 
{ 
    static void Main(string args[]) 
    {
        Application.ApplicationExit += Application_ApplicationExit;
        // your code...
    }

    static void Application_ApplicationExit(object sender, EventArgs e)
    {
        // code to run when application exits
    }
}
Fábio Batista
The finally {} method won't work for applications that set up a new AppDomain or create a new non-background thread and then run most of their code there. The ApplicationExit approach only works for WinForms applications.
Gonzalo
@Gonzalo: The OP explicitly states that he's writing a simple console application.
Adam Robinson
@Adam: a console application, by definition, does not use the System.Windows.Forms.Application class.
Gonzalo
@Gonzalo: My comment was directed at your first comment (about the `finally` clause), not about your objection to `ApplicationExit`.
Adam Robinson
@Adam: ok, nevermind then. I was referring to the second sample in this answer.
Gonzalo