tags:

views:

33

answers:

1

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
}
+2  A: 

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 WithEvents modifier on controls in a WinForm application. The outer Form class subscribes and reacts to these events. This does not cause a memory leak though because the item to which you are subscribed, the Control instances, have roughly the same lifetime as the subscriber, the Form.

In the case where the lifetimes do differ then yes, setting the field to Nothing will cause you to unsubscribe from the event and prevent a possible memory leak.

JaredPar