【问题标题】:C# Cross thread operation not valid after invokedC#跨线程操作在调用后无效
【发布时间】:2023-04-07 15:44:01
【问题描述】:

我遇到了跨线程操作的问题。

我有以下方法

 private void UpdateLabel(string text)
    {
        if (this.richTextRxMessage.InvokeRequired)
        {
            this.Invoke(new Action(() => this.UpdateLabel(text)));
            return;
        }
        else
        {
            this.richTextRxMessage.AppendText(text);
        }
    }

我称之为

UpdateLabel(richTextRxMessage.Text + szData);

我不明白为什么我仍然得到这个异常

【问题讨论】:

  • 您也无法在调用中访问 Text 属性。将其设为 UpdateLabel(szData) 并让 UpdateLabel 使用 Text 属性。

标签: c# multithreading invoke


【解决方案1】:

定义一个类似的委托

  public delegate void UpdateFormText(string text);

然后改变你的方法

private void UpdateLabel(string text)
{
    if (!this.richTextRxMessage.InvokeRequired)
    {
        this.richTextRxMessage.Text=text;

    }
    else
    {
        var s = new UpdateFormText(UpdateLabel);
        Invoke(s, new object[] { text});
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-15
    • 1970-01-01
    • 1970-01-01
    • 2020-08-08
    • 1970-01-01
    • 1970-01-01
    • 2011-07-11
    相关资源
    最近更新 更多