Search code examples
.netwpfdestructormessagebox

Can I call MessageBox.Show() in a Window destructor (finalizer)?


Tried calling MessagBox.Show() in the destructor of a Window class, but it did nothing. I have two separate Window classes in my program, and in each of their destructors I tried this, and even if I close one window and leave the other open, the MessageBox in the destructor of the closed window is not shown.

The two destructors look like this:

~MainWindow()
{
    MessageBox.Show("Exit Main Window", "Exit Main Window", MessageBoxButton.OK, MessageBoxImage.Information);
}

Solution

  • The finalizer (aka destructor) in C# is not like the destructor in for example C. It's not a place where you clean up after the object instance.

    You should use the events in the window object to catch such things instead.

    In an object that implements the IDisposable interface, the finalizer is only run if the object is not disposed properly. The Dispose method typically uses the GC.SuppressFinalize method to remove the object from the finalizer queue, so normally the finalizer is not called at all. The cleanup is done by the Dispose method.

    If the finalizer is called, it's by a separate thread run by the garbage collector. It's not the main thread of your application, so you can't do anything GUI related in the finalizer. The finalizer would be called when the object is about to be garbage collected, so that won't happen right after it becomes unused, but some time after that.

    Also, even if the object is not disposed properly, it's not guaranteed that the finalizer is run. When the application is closed, the garbage collector will run finalizers from objects in the finalizer queue for a while, but after a specific amount of time it will just give up and kill off all the objects without calling the finalizer.