检查InvokeRequired时发生Stackoverflow错误

Hoo*_*och 3 .net c# stack-overflow multithreading invokerequired

我在执行InvokeRequired时遇到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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

dri*_*iis 13

这是因为什么时候InvokeRequired是真的,你一次又一次地调用完全相同的方法.您需要使用Invoke以便将方法安排在UI线程上运行.在这种情况下,InvokeRequired将为false,并且您的代码将运行到if您实际显示对话框的分支中.

将您的代码更改为以下内容:

if(InvokeRequired) 
{
    Func<DialogResult> showMsg = () => ShowMessage(msg, caption, buttons);
    return (DialogResult)Invoke(showMsg);
}
Run Code Online (Sandbox Code Playgroud)