6

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?

Kevin DiTraglia
  • 25,746
  • 19
  • 92
  • 138
  • is this recursion? if so, why are you using recursion? SetLabelText probably shouldn't make a call to itself for UI updating. – jordan Nov 15 '12 at 21:46
  • @jordan.peoples this recursion would only happen once at most, while changing from a background thread to the UI thread. – Mario S Nov 15 '12 at 21:52
  • You should probably check `if (this.IsHandleCreated) ...` – canon Nov 15 '12 at 21:55
  • 1
    possible duplicate of [How to stop BackgroundWorker on Form's Closing event?](http://stackoverflow.com/questions/1731384/how-to-stop-backgroundworker-on-forms-closing-event) – Hans Passant Nov 15 '12 at 21:58
  • this question already has an answer it's a question at FAQ link: [Link](http://stackoverflow.com/questions/661561/how-to-update-the-gui-from-another-thread-in-c) – Nick V Nov 15 '12 at 21:58
  • 1
    @NickV I believe that's the question I based this code off of, but doesn't seem to mention the case where invokes are fired while the form is closing (unless I'm missing something). – Kevin DiTraglia Nov 15 '12 at 22:01
  • @HansPassant do you think the solution to that answer is the best way to go about this? I suppose it makes sense to give the background worker's a heads up and make sure they close cleanly before allowing the app to close. – Kevin DiTraglia Nov 15 '12 at 22:24
  • I think the OP has no idea what he is talking about.... – DotNetRussell Mar 07 '13 at 15:41

1 Answers1

1

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:

Community
  • 1
  • 1
Matt Smith
  • 17,026
  • 7
  • 53
  • 103