Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 366
Kevin DiTraglia Avatar asked Nov 15 '12 21:11

Kevin DiTraglia


1 Answers

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:

  • ObjectDisposedException on call to Form's Invoke when it hasn't been Disposed
like image 195
Matt Smith Avatar answered Sep 21 '22 21:09

Matt Smith