-1

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

下面是我编写的一个方法,它尝试从 RichTextControl 获取文本并返回它。

    /** @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' 从创建它的线程以外的线程访问。

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

4

1 回答 1

4

问题是您仍在访问错误线程上的文本框。您需要返回 的结果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()它。可以直接退货。

于 2012-04-10T22:24:33.357 回答