Is it necessary to set to Nothing(in Dispose()) all WithEvents fields?
Apparently Handles keyword adds handlers to such fields, but does not remove it until this field is not Nothing, and this can generate memory leaks?!.
This should be specially actual on cases like
class Foo
{
Private WithEvents _bar as Bar
Public Sub New(ByVal bar as Bar)
_bar = bar
End Sub
Private Sub Bar_Changed(ByVal sender as Object, _
ByVal e as EventArgs) Handles _bar.Changed
'... '
End Sub
}
This can generate memory leaks if the object to which you are subscribed lives longer than the subscriber. In the majority of cases this is not true.
Take WinForms for instance. Typically you see the
WithEventsmodifier on controls in a WinForm application. The outerFormclass subscribes and reacts to these events. This does not cause a memory leak though because the item to which you are subscribed, theControlinstances, have roughly the same lifetime as the subscriber, theForm.In the case where the lifetimes do differ then yes, setting the field to
Nothingwill cause you to unsubscribe from the event and prevent a possible memory leak.