Matt
Matt

Reputation: 2679

C# Error on Close

When I close my C# application, I am getting the a windows sound that indicates an error. However, when I debug through the close process, I get all the way back up into the Program class...

It gets past Application.Run(..), exits the static void Main() function, and then makes the error noise.

Other than the noise there is nothing indicative of an error. I don't even know where to begin looking! Any ideas?

Upvotes: 2

Views: 1413

Answers (4)

Henk Holterman
Henk Holterman

Reputation: 273179

Something is going wrong in the cleanup, that could be very hard to find. There are two ways to attack this:

Enhance the chances of detecting it while you're still in control (in Main) by wrapping everything in your Main in a try/catch and add some code after the Application.Run to get as much of the cleanup going as possible. A few things I can think of:

GC.Collect(); 
GC.WaitForPendingFinalizers();
Thread.Sleep(1000);
GC.Collect(); 
GC.WaitForPendingFinalizers();

Collect at least 2 times, maybe more. In the same spirit, add a few Application.DoEvents() in the OnClosing of the MainForm.

The other approach is more dependent on your code, to take a stab in the dark: look for all static fields/properties you can set to null and Disposable objects you can Dispose deterministically on Exit.

And all this in combination with Fredrik Mörks suggestion for the UnhandledException event.

Upvotes: 0

Doug L.
Doug L.

Reputation: 2716

Do you have any code that raises custom events? Could these processes still be running when the app tries to close in real-time?

Do you have any custom Dispose code that could be running at time of close?

Upvotes: 0

Fredrik Mörk
Fredrik Mörk

Reputation: 158309

One thing that you could to in order to maybe get some information is to hook up event listeners for the AppDomain.UnhandledException and Application.ThreadException events. It's a long shot, but may provide some info. You could add the following in the beginning of the Main function to set them up, and have them show any exception info in a message box:

static void Main()
{
    AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(delegate(object sender, UnhandledExceptionEventArgs e)
    {
        MessageBox.Show(e.ExceptionObject.ToString());
    });
    Application.ThreadException += new ThreadExceptionEventHandler(delegate(object sender, ThreadExceptionEventArgs e)
    {
        MessageBox.Show(e.Exception.ToString());
    });

    // run your app
}

Upvotes: 3

Chris Van Opstal
Chris Van Opstal

Reputation: 37537

It only happens when you close your app or does it happen when you close any app?

My first thought would be that someone changed your windows sound scheme and set the close program sound to mess with you :).

Upvotes: 1

Related Questions