在不同线程上更新UI的正确方法

Kev*_*lia 6 c# user-interface asynchronous winforms

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

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;
}
Run Code Online (Sandbox Code Playgroud)

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

Mat*_*ith 1

您收到的 ObjectDisposeException 很可能是由于在调用(在队列中)尚未完成的情况下关闭表单而导致的。您要么需要在允许表单关闭之前允许调用完成,要么必须处理 ObjectDisposeException。

看: