0

A quick question about concurrency in C#. I have in my code the following method to update a textbox:

    public void diag(string text)
    {
        if (InvokeRequired)
        {
            Invoke(new Action<string>(diag), text);
        }
        else
        {
            tbDiag.Text += text;
        }
    }

This method gets called in any number of methods in my program to report stuff. Among them, it gets called in the ReportProgress of a BackgroundWorker: this happens periodically every few tens of milliseconds. If I close the form (and the application) without stopping the BackgroundWorker, i get a System.InvalidOperationException because the TextBox has been disposed.

Is there a way to prevent this from the handler for the FormClosing event? Either cancelling the running delegate or waiting for its completion would be fine, just as long as I can get to prevent that exception being thrown. What I would like to avoid is having to keep a direct reference to the delegate.

I apologize if this was answered already somewhere else. I have been googling this to no avail.

Thank you.

Bovaz
  • 375
  • 6
  • 20
  • 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) – cbr Aug 11 '14 at 01:59
  • 1
    @GrantWinney That would still give the exception because the textbox might be disposed between the check and the instruction – Bovaz Aug 11 '14 at 16:08
  • @GrawCube I was aware of that possible workaround and I might end up resorting to that. However that does not really stop/cancel the delegate, but rather wait for the possible source of delegates to stop. On the one hand, I think that might not prevent the exception if many delegates are queued. On the other hand, if I have many parallel operations calling different delegates that kind of solution does not seem to scale very well, I think. – Bovaz Aug 11 '14 at 16:12

0 Answers0