Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 检查invokererequired时发生Stackoverflow错误_C#_.net_Multithreading_Stack Overflow_Invokerequired - Fatal编程技术网

C# 检查invokererequired时发生Stackoverflow错误

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

我在执行InvokeRequest时遇到stackverflow错误

System.StackOverflowException未处理

如何修复它? 我查看详细信息时没有任何信息

固定版本:

    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
或类似类型。