跨线程操作无效:控制从创建它的线程以外的线程访问的“richtxtStatus”

本文关键字:线程 访问 richtxtStatus 创建 无效 操作 控制 | 更新日期: 2023-09-27 18:30:45

可能的重复项:
跨线程操作无效:从创建它的线程以外的线程访问的控件

下面是我编写的一种方法,它尝试从富文本控件获取文本并将其返回。

    /** @delegate */
    private delegate string RichTextBoxObtainContentsEventHandler();
    private string ObtainContentsRichTextBox()
    {
        if (richtxtStatus.InvokeRequired)
        {
            // this means we're on the wrong thread!  
            // use BeginInvoke or Invoke to call back on the 
            // correct thread.
            richtxtStatus.Invoke(
                new RichTextBoxObtainContentsEventHandler(ObtainContentsRichTextBox)
                );
            return richtxtStatus.Text.ToString();
        }
        else
        {
            return richtxtStatus.Text.ToString();
        }
    }

但是,当我尝试运行它时,出现以下异常:跨线程操作无效:控制从创建它的线程以外的线程访问的"richtxtStatus"。

如何修改上面的代码以允许我返回内容?

跨线程操作无效:控制从创建它的线程以外的线程访问的“richtxtStatus”

问题是您仍在错误的线程上访问文本框。您需要返回Invoke()的结果,而不仅仅是调用,忽略结果,然后执行您首先试图避免的事情。此外,您不需要将其包装在事件处理程序中;只需再次调用当前方法即可。

if (richtxtStatus.InvokeRequired)
{
    // this means we're on the wrong thread!  
    // use BeginInvoke or Invoke to call back on the 
    // correct thread.
    string text = (string)richtxtStatus.Invoke(ObtainContentsRichTextBox);
    return text;
}

最后,.Text已经是一个字符串,因此无需对其调用.ToString()。可以直接退货。