C# 检查invokererequired时发生Stackoverflow错误
我在执行InvokeRequest时遇到stackverflow错误 System.StackOverflowException未处理 如何修复它? 我查看详细信息时没有任何信息 固定版本:C# 检查invokererequired时发生Stackoverflow错误,c#,.net,multithreading,stack-overflow,invokerequired,C#,.net,Multithreading,Stack Overflow,Invokerequired,我在执行InvokeRequest时遇到stackverflow错误 System.StackOverflowException未处理 如何修复它? 我查看详细信息时没有任何信息 固定版本: public DialogResult ShowMessage(string msg, string caption, MessageBoxButtons buttons) { if (InvokeRequired) { Func&l
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);
}
}
公共对话框结果显示消息(字符串消息、字符串标题、MessageBox按钮)
{
如果(需要调用)
{
Func m=()=>MessageBox.Show(消息、标题、按钮);
返回(DialogResult)调用(m);
}
其他的
{
返回MessageBox.Show(消息、标题、按钮);
}
}
这是因为当invokererequired
为真时,您会一次又一次地调用完全相同的方法。您需要使用,以便计划在UI线程上运行该方法。在这种情况下,InvokeRequired
将为false,代码将运行到实际显示对话框的if
分支中
将代码更改为以下内容:
if(InvokeRequired)
{
Func<DialogResult> showMsg = () => ShowMessage(msg, caption, buttons);
return (DialogResult)Invoke(showMsg);
}
if(需要调用)
{
Func showMsg=()=>ShowMessage(消息、标题、按钮);
返回(DialogResult)调用(showMsg);
}
您会遇到stackoverflow,因为ShowMessage方法被卡在一个不定循环中,因为它在“InvokeRequired”时会反复调用自己。只是一个注释,最好将代码发布在这里,而不是图像。这样,根据您已有的代码更容易创建正确的代码示例。您需要将委托类型更改为Func
或类似类型。