Reputation: 29693
I'm getting a stackverflow error while executing InvokeRequired.
System.StackOverflowException was unhandled
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);
}
}
Upvotes: 4
Views: 1893
Reputation: 164341
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);
}
Upvotes: 14
Reputation: 8758
You're getting a stackoverflow because the ShowMessage method is stuck in an infinitive loop, because it calls itself over and over when "InvokeRequired"
Upvotes: 4