How do I keep a new form getting messages meant for older diposed form
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.
No comments:
Post a Comment