Question

When I create and show a form and close (terminate) the application when the form is still open, a stack overflow exception is thrown.

Showing the form:

private static void OpenSettings(Object sender, EventArgs e)
{
    ActionLog.Write("Opened Settings");
    form_Settings f_Settings = new form_Settings();
    f_Settings.Show();
}

Closing my Application by using the context menu callback:

private static void Quit(Object sender, EventArgs e)
{
    ActionLog.Write("Exit");
    Settings.Serialize();
    Environment.Exit(0);
}

the exception is thrown in the GUI.form_Settings.Dispose function. The function never exits and causes an infinite recursion.

If I don't have the window opened when I close my application, everything goes fine.

How is that?

// Edit:

protected override void Dispose(bool disposing)
{
    if (disposing && (components != null))
    {
        components.Dispose();
    }
    base.Dispose(disposing);
}

Guess that's pretty standard, I couldn't find any other definitions. Also I want to mention that I'm using a custom framework (https://github.com/viperneo/winforms-modernui), could this be a reason for this behavior?

Was it helpful?

Solution 2

I just found out that the custom framework ( https://github.com/viperneo/winforms-modernui ) is not working as intended. Everything works fine with the regular Windows Forms, no exception is thrown. But for some reason when using the framework, the exception is thrown if a form is not disposed before the application quits. Hopefully someone may read this when considering using this framework.

Thanks to Hans Passant for the hint regarding the custom framework!

OTHER TIPS

Probably you are victim of a recursive call. Look at the stack trace when the exception is thrown and you will see which methods are called repeatedly. Probably one of the actions in Quit is triggering an event which calls Quit again.

See Recursion on Wikipedia.


UPDATE (in response to your comment)

I would add a flag, telling whether the object was disposed.

private bool _disposed = false;

protected override void Dispose(bool disposing)
{
    if (!_disposed) {
        _disposed = true;

        if (disposing && (components != null))
        {
            components.Dispose();
            components = null; // Now they cannot be disposed again.
        }

        base.Dispose(disposing);
    }
}

But try to understand why it is called recursively. There might be another bug hidden somewhere else.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top