I sometimes use delegates for broadcasting
"StateChang ed" events, i.e. if I have multiple forms
and/or controls that need updating at the same time
as the result of a change in a global/common object,
I keep local references to this object in each UI
object, e.g.
Private WithEvents _tools As RepeatTools
and catch messages in an event handler like this:
Private Sub _tools_StateCha nged(ByVal sender As Object, ByVal
e As System.EventArg s) Handles _tools.StateCha nged
If Me.AcceptEvents Then
Try
DisplayProperti es(sender)
Finally
Me.EnableEvents ()
End Try
End If
End Sub
In the past, I have had problems with _tools_StateCha nged
events still firing after a form has been closed - as if parts of
the form is still alive somewhere. Of course, once the event
fires and code attempts to access the now disposed controls
on the form, an exception is thrown.
Until now, I have solved this by adding something like this:
Private Sub frmRepeatPrevie w_FormClosing(B yVal sender As
Object, ByVal e As System.Windows. Forms.FormClosi ngEventArgs) Handles
Me.FormClosing
_tools = Nothing
End Sub
to ensure that _tools would no longer fire any events in that
form.
HOWEVER: Now I have encountered a situation where
_tools_StateCha nged is firing even though _tools has been
set to Nothing, i.e. to fix it, I had to insert a "sentinel":
Private Sub _tools_StateCha nged(ByVal sender As Object, ByVal
e As System.EventArg s) Handles _tools.StateCha nged
If _tools Is Nothing Then
Return '<<<<<< Yes, we actually end up here!
End If
If Me.AcceptEvents Then
Try
DisplayProperti es(sender)
Finally
Me.EnableEvents ()
End Try
End If
End Sub
And now everything works, but I have plenty of code like
this without such a check and I am concerned that something
else might fail someday, so rather than hunt through my code
to apply the same fix everywhere, could someone please explain
to me what it is I do not understand and what I need to do to
ensure that such delegates stop firing events?
TIA,
Joergen Bech
Comment