C# › Delegates, Events & Lambdas
How would you implement the 'weak event pattern' to prevent event subscribers from causing a memory leak by keeping the publisher alive indefinitely?
AdvancedAnswer
A standard event subscription (+=) creates a STRONG reference from the publisher to the subscriber, meaning the subscriber can't be garbage collected as long as the publisher is alive and the subscription remains — the weak event pattern uses WeakReference (or a dedicated helper like WeakEventManager) to hold a WEAK reference to the subscriber instead, letting it be collected even if never explicitly unsubscribed.
public class WeakEventSubscription {
private readonly WeakReference<Action> _weakHandler;
public WeakEventSubscription(Action handler) { _weakHandler = new WeakReference<Action>(handler); }
public void Raise() {
if (_weakHandler.TryGetTarget(out var handler)) handler();
// if the target was collected, TryGetTarget returns false -- no leak, no crash
}
}Real-world example Preventing a long-lived singleton service (like an app-wide event bus) from indefinitely keeping short-lived UI elements alive via forgotten event subscriptions.