Search code examples
.netvb.netevent-handlingdispose

When and where to call the RemoveHandler in VB.NET?


I am working to a VB.NET windows forms projet in .NET 1.1. And I have this type of architecture, very simplified.

Public MustInherit Class BaseTestLogic

  Private _TimerPoll As Timer

  Public Sub New(ByVal sym As SymbolFileMng, ByVal cfg As LampTestConfig, ByVal daas As DaasManager, ByVal mcf As Elux.Wg.Lpd.MCFs.VMCF)

    AddHandler _TimerPoll.Tick, AddressOf TimerPoll_Tick

  End Sub

End Class

Public Class SpecificTestLogic
  Inherits BaseTestLogic      

End Class

Depending of the type of test I am doing I create an instance of a specific test derived from BaseTestLogic. But I found that after hundreds of object creations I can have StackOverflow exception.

I checked my code and saw that I forgot to remove the handler to Timer Tick. The question is, where and when is it correct to remove hadler?

Do I need to implement the IDisposable interface in the base class and RemoveHandler in Dispose?


Solution

  • You may go along with removing the handler when the Dispose is called, but a purist would say that "you shouldn't abuse IDisposable for purposes other than disposing unmanaged resources".

    Another option is to remove the handler at the Finalize method.

    You can also feel comfortable about removing the handler at several different places, if that makes any sense in your design. Removing an already removed handler will not cause any issue - unless the event is a Custom Event and its AddHandler/RemoveHandler implementations don't match the behavior of non-custom events (which is simply to use [Delegate].CombineDelegate/[Delegate].Remove). Just don't tell your purist friends about it; they won't comply.