Search code examples
.netvb.neteventsevent-handlingaddhandler

Where to "destroy" Handlers in VB.NET classes?


I have some class (a user control) MyUserControl that rises events.

I use it in a form MyForm, in that, for some reasons I am forced to use AddHandler instead of WithEvents<>Handles pair.

I use AddHandlers in the MyForm_Load method.

Now. Adding handler is OK, the question now is where to remove this handler. Should it be done in the Finalize method of MyForm? à la

Protected Overrides Sub Finalize()
  RemoveHandler _myCtrl.Action1Performed, AddressOf MyControl_Action1Performed  
  RemoveHandler _myCtrl.Action2Performed, AddressOf MyControl_Action2Performed  
  RemoveHandler _myCtrl.Action3Performed, AddressOf MyControl_Action3Performed  
End Sub

Solution

  • When the container control (such as your form) is disposed, all of its event handlers will be automatically removed and disposed. This cleanup happens for you automatically because neither your user control nor its container form exist anymore.

    The only time you really need to worry about calling RemoveHandler is if you're hooking up event handlers to objects that are expected to have a significantly longer lifespan than their containers. In that case, it's possible to create a memory leak because that object cannot be garbage collected as long as that handler is subscribed. You can read a much more comprehensive case study here on Tess Ferrandez's blog. This is not a problem if both objects go "out of scope" at the same time.

    EDIT: If you still feel that you absolutely need to remove the handler (perhaps you're obsessive compulsive?), you can go ahead and do it in the form's Dispose method. A purist might balk at the use of IDisposable for something like this, but you won't see any ill results. You do want to make sure that you don't implement the Finalize method for this, though. There's just no point: the finalizer method won't get called until there are no more strong references to the object, but the only possible harm in failing to call RemoveHandler is that a container will hold onto a reference to that object longer than necessary. You're fooling yourself by trying to remove event handlers in the Finalize method.

    Also keep in mind that it really doesn't matter where exactly you do it, because the purpose of AddHandler/RemoveHandler is to allow you to add and remove event handlers dynamically. You're allowed to call them anywhere in your code that you want.