Delegates, Events and object lifetime

(Setting WithEvents to Nothing)

Under the covers, Events use Delegates, and Delegates store a reference to the object in which the method address resides. (Sender property of Delegate).

One major problem with this, is if you have shared components or components with shared internal components (e.g. an instance object that use an internal factory for monitoring events on an application basis).  In this case the component can be kept alive after the form it was in closes, and in fact the component can keep the form alive as it has a reference to it.

This problem applies to both C# and VB.NET.  In fact it is a problem each language needs to address.  VB.NET is well designed for declarative event wiring, using clean property sets and gets to wire and unwire events.   However it fails to utilize that.  Ideally VB.NET should create an UnWire method, and in that method set every WithEvents variable to nothing.  The UnWire would be called from the Dispose method.

This pattern would allow safe removal of any hanging circular references that may be rooted via shared components.  Furthermore, it would allow components that use an internal factory pattern to monitor the remove handler to determine when to release expensive resources.

This is a simple addition to the “code spit” VB.NET does and would not impact performance.  It would help ensure memory is cleaned up properly.

1 Comment so far

  1.   Jonathan Allen on August 12th, 2004          

    Do you see an unwire method being generated for all classes that have WithEvents fields? Or just forms?