Friday, 20 April 2012

Weak Event Handlers

Why would you need to use a Weak Event handler? Take a look at this example of normal events and handlers:

Notice how the Console window is empty. The Subscriber finalizer ~Subscriber() which writes to the console window has not been called meaning our subscriber is still in memory. This is due to the Publisher event holding a strong reference to the Subscribers event handler (see the watch window).

Why not just implement IDispose and unsubscribe from the event?

This is the ideal scenario but you are relying upon our Publisher being considerate enough to call dispose on the Subscriber. This means we can remove the event handler, notice how the publishers event is now null, which means the GarbageCollector can collect our subscriber.

But what happens if the Publisher forgets to “dispose” of the subscriber? We still have a memory leak.

Weak Reference Events to the rescue!

We can see here in the watch window that the publishers event still has a reference to the subscribers event handler. But the subscriber has been disposed…. cool!