简体   繁体   中英

Proper Way to Update UI on Different Thread

So I have this simple class that updates my labels, and it gets accessed by different threads and reports progress of my application. It works fine however when closing this app this code always throws an error about trying to access something that is disposed.

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;
}

Is this not the proper way to go about this? Is there something I need to add to make sure it doesn't try to perform updates on the UI while the app is closing?

The ObjectDisposedException you are receiving is most likely due to letting the Form close while having Invokes (in the queue) that haven't yet completed. You'll either need to allow the Invokes to complete before allowing the form to close or you'll have to handle the ObjectDisposedException.

See:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM