skip to content

Handler Leaks

A long-lived publisher keeps every subscriber alive until it unsubscribes, and an inline lambda handler cannot be removed. Interviewers ask how to find and fix the leak.

on this pageshow

questions

5

In C#, when a document window subscribes to a settings service's event, which of the two objects does the subscription keep alive, and why?

level: juniorimportance: must knowfreq 70%

answer

  1. direction of the reference
  2. what += stores, and where
  3. Delegate.Target
  4. the publisher's invocation list

basics

~20 s

The publisher keeps the subscriber alive. The += operator stores a delegate in the settings service's event field, and that delegate's Target is the window or a closure that captured it, so the service reaches the window until it unsubscribes.

solid answer

~30 s

The reference runs from the publisher to the subscriber. `settings.Changed += OnSettingsChanged` creates a delegate that records the method in `Delegate.Method` and its receiver, the window, in `Delegate.Target`, and appends it to the invocation list held in the service's event field. As long as the service is reachable, so is the window, its controls and the document it loaded. The subscription adds nothing in the other direction, so a short-lived publisher with a long-lived subscriber is harmless. The dangerous shape is a long-lived publisher, such as an app-wide service or any `static` event, with short-lived subscribers that never call `-=`.

code

csharp · 20 lines
csharp
var settings = new SettingsService();
var window = new DocumentWindow(settings);

Delegate stored = settings.Subscribers()[0];
Console.WriteLine(ReferenceEquals(stored.Target, window));  // True: the service holds the window
Console.WriteLine(stored.Method.Name);                      // OnSettingsChanged

sealed class SettingsService
{
    public event EventHandler? Changed;
    public Delegate[] Subscribers() => Changed?.GetInvocationList() ?? [];
}

sealed class DocumentWindow
{
    public DocumentWindow(SettingsService settings) =>
        settings.Changed += OnSettingsChanged;   // stores (this, OnSettingsChanged)

    private void OnSettingsChanged(object? sender, EventArgs e) { }
}

go deeper

for a junior

Recall the direction: the publisher's event field holds a delegate, and the delegate's Target is the subscriber. Say that unsubscribing with -= is what breaks the chain.

for a middle

Explain what a delegate records for an instance method versus a capturing lambda, and why a short-lived publisher with a long-lived subscriber is harmless.

for a senior

Show you can predict a leak from lifetimes alone: app-wide services and static events with short-lived subscribers, and where the matching -= belongs.

for a principal

Frame the lifetime mismatch as an architectural property: which components may expose long-lived events, and how ownership of each subscription is made explicit.

## What `+=` actually stores An **event** in C# is, for a field-like declaration such as `public event EventHandler? Changed;`, a private field of a delegate type plus an `add` and a `remove` accessor that outside code reaches through `+=` and `-=`. When a window writes ```csharp settings.Changed += OnSettingsChanged; ``` the compiler turns the method group `OnSettingsChanged` into a new `EventHandler` delegate. A delegate built from an instance method stores two pieces of information: - **`Delegate.Method`** — the method to call (`OnSettingsChanged`); - **`Delegate.Target`** — the object to call it on, which here is the window itself. The `add` accessor then combines that delegate into the service's existing delegate, producing a new **invocation list** that is stored back in the service's field. Nothing is stored in the window. The window only *used* its reference to the service to call the accessor. ## The direction of the reference Garbage collection in .NET keeps an object alive while it is **reachable** from a root (a static field, a local on a running thread, and so on). After the subscription, the reachability chain is: 1. something long-lived holds the settings service; 2. the service's `Changed` field holds the multicast delegate; 3. the delegate's `Target` holds the window; 4. the window holds its controls, its document buffer and whatever else it owns. So the **publisher keeps the subscriber alive**, never the reverse. That is why the official C# guide on subscribing tells you to unsubscribe before you dispose of a subscriber: until you do, the publisher's multicast delegate references the subscriber's handler, and garbage collection will not delete the subscriber. | Publisher lifetime | Subscriber lifetime | Outcome if nobody calls `-=` | |---|---|---| | Long (app-wide service) | Short (a window) | **Leak**: every closed window stays reachable | | `static` event | Anything | **Worst case**: the field lives as long as its type is loaded | | Short (a request, a dialog's own button) | Long (a logger) | Harmless: the publisher dies and takes its list with it | | Same object graph (a view and a child it owns) | Same | Harmless: they become unreachable together | ## Lambdas and captured variables A lambda handler changes *what* the delegate's `Target` is, not the direction: - a lambda that uses `this` or instance members compiles to a method on the window's class, so `Target` is the window; - a lambda that captures locals compiles to a method on a **compiler-generated closure class**; `Target` is that closure object, which holds the captured variables, and if one of them is the window, the window is reachable through it; - a lambda that captures nothing at all compiles to a method on a compiler singleton whose delegate is cached, so it holds nothing of the window. Either way, the service is still the object holding the chain. Method-group handlers are no safer than lambdas here: an instance method group always records its receiver. ## Static events A `static event` is backed by a static field. A static field is reachable for as long as its type is loaded, which for an ordinary application is the whole process. There is no publisher instance that can die and release the list, so every subscriber that forgets `-=` lives until the process ends. This is why many teams treat static events as a code smell for anything a short-lived object subscribes to. ## How to reason about it in an interview - Name the direction first: **publisher → delegate → subscriber**. - Then compare lifetimes: the leak needs a publisher that outlives its subscribers. - Then name the fix: call `-=` with an equal delegate when the subscriber's life ends, typically in its `Dispose` or close handler, or let the subscriber hold a subscription object it disposes. Whether you could instead use a weak reference is a separate design question with real trade-offs. A common trap is to describe this as "events leak". They do not; a subscription is just a strong reference stored in the publisher. Whether that reference becomes a leak depends entirely on which of the two objects is supposed to outlive the other. ## Seeing it for yourself You can observe the reference without any tooling. `GetInvocationList()` on the event's delegate, called from inside the publisher, returns one `Delegate` per handler, and each one exposes `Target` and `Method`. In the snippet below, the first entry's `Target` is the very window object that subscribed, and its `Method` is `OnSettingsChanged`. That one property is the whole leak in miniature: as long as the service keeps that delegate, the window cannot be collected. Two consequences follow for everyday code: - **Unsubscribing is the subscriber's job, but the publisher's lifetime decides whether it matters.** Code reviewers should ask "does this publisher outlive the subscriber?" for every `+=` they see. - **Removing the handler needs an equal delegate.** `settings.Changed -= OnSettingsChanged;` works because the new delegate has the same `Target` and `Method`; how a second, separately written lambda fails that test is a topic of its own.

  • What changes if the settings service exposes its Changed event as a static event?
    The invocation list then lives in a static field, which stays reachable as long as its type is loaded, normally the whole process. No service instance can become unreachable and release it, so every subscriber that never calls `-=` is kept alive until the process ends. That makes a forgotten unsubscribe on a static event the worst version of this leak.
  • If the window subscribes with a lambda that captures a local variable, what does the service hold?
    The delegate's `Target` becomes a compiler-generated closure object that stores the captured variables, and the method is generated on that closure class. The service holds the closure, and the closure holds whatever it captured; if it captured the window, the window stays reachable exactly as with a method group. Only a lambda that captures nothing holds no reference to the window.

A subscription is like leaving your phone number on a club's mailing list: the club keeps your number, not the other way round, and you stay on the list until you ask to be taken off.

  • Subscribing to an event keeps the publisher alive, so the subscriber is safe.
  • The garbage collector removes handlers whose subscriber is no longer used anywhere else.
  • C# events hold their subscribers through weak references.
  • Method-group handlers hold no reference to the object; only lambdas do.
  • Every event subscription that is never removed is a memory leak.
open as a page

In C#, why does settings.Changed -= (s, e) => window.Refresh() fail to remove the handler that an identical lambda added with +=?

level: middleimportance: must knowfreq 65%

basics

~20 s

Each lambda expression compiles to its own method, so the lambda written after -= is a different delegate from the one added. Delegate.Remove finds no equal entry and silently leaves the list unchanged; store the delegate and remove that instance.

open as a page

A C# desktop app's memory grows with every document window closed, and each window subscribed to a long-lived settings service's Changed event; why, and how do you fix it?

level: seniorimportance: must knowfreq 60%

basics

~20 s

Each closed window is still reachable: the settings service's Changed field holds a delegate whose Target is the window. Fix it by unsubscribing with an equal delegate when the window closes, typically in Dispose, and making sure Dispose is called.

open as a page

In C#, why does a weak event that stores each handler as a WeakReference<EventHandler> stop firing almost at once, and what should it hold weakly instead?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Only the WeakReference points at the delegate object, so the next collection frees it while the subscriber lives on. A weak event must hold the subscriber, the delegate's Target, weakly and keep the method strongly, then prune dead entries.

open as a page

As lead of a large C# desktop codebase, what rule would you set for event subscriptions from short-lived views to long-lived services, and why?

level: principalimportance: should knowfreq 30%

basics

~20 s

Make subscription ownership explicit: long-lived services return an IDisposable subscription that the view disposes with its own lifetime, static events are banned for view code, and weak events are kept for publishers that cannot know their subscribers.

open as a page