4

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);
        }
    }
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
Hooch
  • 28,817
  • 29
  • 102
  • 161
  • 3
    Just a note, it's considered best practice to post the code here, instead of an image. It's easier to create a correct code example that way, based on the code you already have. – driis Nov 06 '11 at 12:21

2 Answers2

14

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);
}
driis
  • 161,458
  • 45
  • 265
  • 341
4

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

Ron Sijm
  • 8,490
  • 2
  • 31
  • 48