Unsubscribing events: How VB Handles it

Davy Brion posted about how events can keep object references alive.  In C# to rid yourself of this issue you have to manually unwire any event handler you wired.  In VB, it is a lot easier, all you have to do is use WithEvents and set the variable to nothing. This code is the VB version of Davy’s sample:

 

Public Class Publisher

   Public Event MyEvent As EventHandler

 

   Public Sub FireEvent()

      RaiseEvent MyEvent(Me, EventArgs.Empty)

   End Sub

 

End Class

 

 

Public Class GoodSubscriber

   Implements IDisposable

 

   Private WithEvents _publisher As Publisher

 

 

   Public Sub New(ByVal publisher As Publisher)

      _publisher = publisher

   End Sub

 

 

 

   Private Sub _publisher_MyEvent(ByVal sender As Object, ByVal e As System.EventArgs) Handles _publisher.MyEvent

      Console.WriteLine("the publisher notified the good subscriber of an event")

   End Sub

 

 

 

   Public Sub Dispose() Implements IDisposable.Dispose

      _publisher = Nothing

   End Sub

 

End Class

As long as the variable is declared as WithEvents any event wired up via declarative event handling will be unwired when the variable is set to Nothing.

This is yet another subtle but important example of how declarative coding styles can lead to more robust code.  The above example is minimal, but when you get many events and many objects raising events, the cleanness of the VB way of handling it becomes even more important.  Or in other words in C# you have to make sure you unwire each and every event, in VB you use declarative events syntax and VB handles it for you ;)

This entry was posted in 491, 5726, 6183, 7099, 7341. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>