Search

Categories

.NET Weak Event Handlers – Part I

In .NET when you subscribe to an event providing an instance method as the event handler the event source stores a reference to the target instance for which the event handler will be triggered.

In a scenario where you have short-lived event listeners and event sources with a long lifetime this will pose a problem because the strong reference in the event source will become the sole reason these objects don’t get garbage collected. Depending on the memory footprint of each event listener this may lead to problems in the application.

However, I’ll present another approach to solve this problem, more specifically a helper class that creates weak event handlers used to subscribe to any .NET event without forcing a strong reference to the event listener.

This helper class will support two flavors of weak event handlers:

Reflection based;

Delegate based.

They will share a common base class since both will store a WeakReference to the event listener instance to allow it to be garbage collected if no other references exist.

These weak event handler are created through a static helper class. The contract defined by this helper class is provided here while the full implementation with documentation is available at GitHub where you can also find the NUnit unit tests used to test it.