简体   繁体   中英

window.ShowDialog stackoverflowexception reasons. WPF

What is main reasons for window.ShowDialog() stackOverflowException in WPF? I receive this exception after 10-20 seconds when I call:

if(myWindow.ShowDialog() == true)
{
   //other stuff
}

Window is shows up and works good, but then I receive this exception.

The generic cause of an SOE like this is having an event handler whose code causes the same event to be raised again. A simple example is:

    private void textBox1_TextChanged(object sender, TextChangedEventArgs e) {
        textBox1.Text += "a";
    }

Type a letter, takes about 5 seconds for program to run out of stack space and bomb. Your primary weapon to diagnose exactly which event handler causes this problem is the debugger, look at the Call Stack window. You solve it by using a little helper variable that indicates that you expect the event to be fired again so you can ignore it. Like this:

    bool changingText;

    private void textBox1_TextChanged(object sender, TextChangedEventArgs e) {
        if (changingText) return;
        changingText = true;
        try {
            textBox1.Text += "a";
        }
        finally {
            changingText = false;
        }
    }

The try/finally is not strictly necessary but wise if you expect to keep your program running after an exception.

Surprisingly a stack overflow exception can be caused by repeatedly calling window.ShowDialog asynchronously.

    public MainWindow()
    {
        InitializeComponent();
        TheCallDelegate = TheCall;
        _timer = new DispatcherTimer();
        _timer.Tick += _timer_Tick;
        _timer.Start();
    }

    DispatcherTimer _timer = null;

    void _timer_Tick(object sender, EventArgs e)
    {
        _timer.Dispatcher.BeginInvoke(TheCallDelegate);            
    }

    Action TheCallDelegate;

    void TheCall()
    {
        Window win = new Window();
        win.ShowDialog();
    }

As you can see there is no actual recursion here (or there shouldn't have been) but once the exception happens you can see that the call stack is indeed full. Without looking at how Window.ShowDialog is implemented internally I can't say what is the deeper cause of this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM