0

I have a form that opens and connects to an existing calculation object with a backgroundworker. When the background worker is done a message is sent and the form runs a OnCompletion method. That method will create a messagebox if the calculation fails. Let us assume the calcualtion fails. The user will then get a message about the failure. Now we close the form, open a new instance of the form, and run the calculation again. Again the calculation fails, and the form runs the OnCompletion method and crashes at the messagebox.

MessageBox.Show(this, message, title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

The problem is that "this" (the form) is diposed. If a change the code to test for IsDiposed:

            if (!IsDisposed)
            MessageBox.Show(this, message, title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

Then the messagebox does not get called, but I see that my OnCompletion method immediately runs a second time, IsDiposed is now false, and the messagebox is called correctly.

Although my test to see if the form is disposed solves the problem, I think I must be doing something wrong if my OnCompletion method is called twice.

Note that the double call to OnCompletion only happens if the original form has been closed. After that, every time the calculation is run, the OnCompletion method is called twice, and this.IsDiposed is true the first time and false the second time.

Anyone have an explaination, or suggestion to stop the double call to OnCompletion.

Valamas
  • 24,169
  • 25
  • 107
  • 177
spainchaud
  • 365
  • 3
  • 12
  • This went down-hill when you allowed the worker thread to use the closed form's instance, you'll need to stop this from happening. It is not that difficult, *any* control reference is good enough, there is no need that it be any particular form. So use your main form's reference. Application.OpenForms[0] if really, really necessary. Similarly, if you subscribed an event that the worker generates then you'll need to explicitly unsubscribe it when you allow the worker to continue. – Hans Passant Sep 09 '13 at 22:42
  • The worker does not know about the form, but the unsubscribe idea should work. I added a counter to my form, and found out that closing or disposing it does not get rid of it. It is still recieving the notifications. – spainchaud Sep 09 '13 at 22:49
  • As suggested by Hans, I unsubscribed to the events in the Dispose method of my control. So he has the answer. – spainchaud Sep 10 '13 at 00:00

0 Answers0