Stackoverflow error while checking InvokeRequired

1.8k Views Asked by At

I'm getting a stackverflow error while executing InvokeRequired.

System.StackOverflowException was unhandled

enter image description here

How to fix it? There is no info i View Details.

FIXED VERSION:

    public DialogResult ShowMessage(string msg, string caption, MessageBoxButtons buttons)
    {
        if (InvokeRequired)
        {
            Func<DialogResult> m = () => MessageBox.Show(msg, caption, buttons);
            return (DialogResult)Invoke(m);
        }
        else
        {
            return MessageBox.Show(msg, caption, buttons);
        }
    }
2

There are 2 best solutions below

1
On BEST ANSWER

It's because when InvokeRequired is true, you call the exact same method again and again. You need to use Invoke in order to get the method scheduled to run on the UI thread. In this case, InvokeRequired will be false, and your code will run into the if branch where you actually show the dialog.

Change your code to something along the lines of:

if(InvokeRequired) 
{
    Func<DialogResult> showMsg = () => ShowMessage(msg, caption, buttons);
    return (DialogResult)Invoke(showMsg);
}
0
On

You're getting a stackoverflow because the ShowMessage method is stuck in an infinitive loop, because it calls itself over and over when "InvokeRequired"