【问题标题】:Proper Way to Update UI on Different Thread在不同线程上更新 UI 的正确方法
【发布时间】:2012-11-04 14:18:51
【问题描述】:

所以我有一个简单的类来更新我的标签,它可以被不同的线程访问并报告我的应用程序的进度。它可以正常工作,但是在关闭此应用程序时,此代码总是会引发有关尝试访问已处置的内容的错误。

private delegate void SetLabelTextDelegate(string str1, string str2);
public void SetLabelText(string str1, string str2)
{
    if (this.label1.InvokeRequired || this.label2.InvokeRequired)
    {
        this.Invoke(new SetLabelTextDelegate(SetLabelText), new object[] { str1, str2});
        return;
    }
    this.label1.Text = (str1 == string.Empty) ? this.label1.Text : str1;
    this.label2.Text = (str2 == string.Empty) ? this.label2.Text : str2;
}

这不是解决这个问题的正确方法吗?是否需要添加一些内容以确保它不会在应用关闭时尝试在 UI 上执行更新?

【问题讨论】:

  • 这是递归吗?如果是这样,你为什么要使用递归? SetLabelText 可能不应该调用自身来更新 UI。
  • @jordan.peoples 这种递归最多只会发生一次,同时从后台线程更改为 UI 线程。
  • 你应该检查if (this.IsHandleCreated) ...
  • @NickV 我相信这是我基于此代码的问题,但似乎没有提到在表单关闭时触发调用的情况(除非我遗漏了什么)。

标签: c# winforms user-interface asynchronous


【解决方案1】:

您收到的 ObjectDisposedException 很可能是由于在调用(在队列中)尚未完成时让表单关闭。您要么需要允许 Invokes 在允许表单关闭之前完成,要么必须处理 ObjectDisposedException。

见:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-18
    • 2017-11-01
    • 1970-01-01
    • 2015-12-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多