finally block not executing after Application.Run(new main_form)

685 Views Asked by At

I wanted to have some code execute before my program exited, so I thought that editing to the VS created Program.cs to look like:

...
try
{
    Application.Run(new main_form);
}
finally
{
    special_shutdown_code();
}
...

would do the trick, but my special_shutdown_code() is not being executed when I click the [x] in the upper right corner of the main form. I went back and added print statements:

...
try
{
    System.Console.WriteLine("Before");
    Application.Run(new main_form);
    System.Console.WriteLine("After");
}
finally
{
    System.Console.WriteLine("finally");
    special_shutdown_code();
}
System.Console.WriteLine("post-finally");
...

"Before" was the only output printed.

From what I've read the Application.Run functions should return. I'm at a lost. Any explanations would be appreciated.

This is a C++/CLR + C# + C mixed program, but the main part is C#.

I'm hoping to get an explanation for what is not happening rather than suggestions for how to accomplish the same functionality. I am able to work around this for most cases, but what seemed like the cleanest, easiest to understand, and the right way to do it not working at all confuses me.

2

There are 2 best solutions below

2
On

You could try:

Form mainForm = new MainForm();
mainForm.Closing += delegate(...)
{

};
Application.Run(mainForm);

Not sure if this would actually work...

0
On

I came across the answer while looking into running message pumps on threads without a main form.

There are 3 versions of Application.Run(). I've found very little good information on using the version that takes no arguments. The one I see the most is Application.Run(Form), which I believe ends up calling Application.Run(new ApplicationContext(Form)) possibly after doing some setup. This sets the `ApplicationContext.MainForm