skip to content

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%

answer

  1. who else references the delegate
  2. the delegate is not the subscriber
  3. Target weakly, Method strongly
  4. closures and static methods
  5. ConditionalWeakTable

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.

solid answer

~40 s

The publisher wants to avoid keeping the *subscriber* alive, but `WeakReference<EventHandler>` makes the *delegate* weak, and nothing else references that delegate, so the next collection frees it even though the window is alive. A working weak event stores `WeakReference<object>` to `handler.Target` plus the `MethodInfo` from `handler.Method`, invokes only when `TryGetTarget` succeeds, and prunes dead entries on each raise. Lambdas break it again: a capturing lambda's `Target` is a compiler-generated closure that only the weak entry references, so it is collected at once, and a static method has no `Target` at all. Tying the delegate to the subscriber with `ConditionalWeakTable<TKey,TValue>` handles closures. Trade-offs: reflection or extra invocation cost, and a closed but uncollected subscriber still receives events until a collection runs.

code

csharp · 13 lines
csharp
using System.Runtime.CompilerServices;

var window = new DocumentWindow();
WeakReference<EventHandler> weakHandler = MakeWeak(window);
GC.Collect();
Console.WriteLine($"delegate alive: {weakHandler.TryGetTarget(out _)}");  // False
GC.KeepAlive(window);                                                     // the window is still alive

[MethodImpl(MethodImplOptions.NoInlining)]
static WeakReference<EventHandler> MakeWeak(DocumentWindow window) =>
    new(window.OnSettingsChanged);   // only the weak reference points at this delegate

sealed class DocumentWindow { public void OnSettingsChanged(object? s, EventArgs e) { } }

go deeper

for a junior

Remember that a weak event aims to let the subscriber be collected, and that the subscriber is the delegate's Target, not the delegate.

for a middle

Explain why WeakReference to the delegate dies at once and how storing Target weakly with Method strongly fixes method-group handlers.

for a senior

Name where the pattern breaks, capturing lambdas and static methods, and how ConditionalWeakTable or a ban on closures handles it; state the nondeterminism and cost.

for a principal

Decide where weak events are worth their nondeterminism, usually framework-level publishers with unknowable subscribers, and where explicit unsubscription stays the rule.

## The goal of a weak event A normal C# event keeps every subscriber alive, because the publisher's delegate field references each handler's `Target`. A **weak event** is a publisher-side design that lets a subscriber be collected even if it never unsubscribes. The BCL gives you the building block, `WeakReference<T>`, whose `TryGetTarget(out T target)` returns `false` once the target has been collected, and which, per its source comment, deliberately offers `TryGetTarget` instead of a getter so callers test and use the target in one step. ## The naive version and why it dies The obvious design stores each handler weakly: ```csharp var weak = new WeakReference<EventHandler>(window.OnSettingsChanged); ``` This makes the wrong object weak. `window.OnSettingsChanged` creates a **new delegate object**. The window does not reference that delegate; only the `WeakReference` does. At the next collection the delegate is unreachable and is freed, while the window, the object you cared about, is still alive. The handler stops firing, silently, after an unpredictable delay. The snippet below prints `delegate alive: False` with the window still alive. ## Holding the subscriber weakly instead Split the delegate into its two parts and treat them differently: - **`handler.Target`** — the subscriber. Hold it in a `WeakReference<object>`, so the publisher does not keep it alive. - **`handler.Method`** — a `MethodInfo`. Hold it strongly; it is metadata and keeps no subscriber alive. On raise, call `TryGetTarget`; if it succeeds, invoke the method on the target (with `MethodInfo.Invoke`, or a cached open-instance delegate to avoid reflection cost), and if it fails, remove the entry. This works for method-group handlers, whose `Target` is the subscriber itself. ## Where it breaks: lambdas and static methods | Handler | `Target` | Behaviour with a weak `Target` | |---|---|---| | Method group on the window | the window | Fires while the window lives, then is pruned | | Lambda capturing locals | a compiler closure object | **Collected at the next GC**: only the weak entry referenced it | | Lambda using only `this` | the window | Same as a method group | | Lambda capturing nothing | a cached compiler singleton | Never collected, so it is effectively strong | | Static method | `null` | Nothing to hold weakly; must be stored strongly | The capturing lambda is the trap: the closure is a separate object that nobody but the delegate references, so making it weak kills the handler even though the window it calls into is alive. Two common answers: 1. **Reject or special-case closures**, accepting only method groups (some designs check that the target is not compiler-generated). 2. **Tie the delegate's life to the subscriber** with `ConditionalWeakTable<TKey,TValue>`: key on the subscriber and store the delegate as the value. The runtime comment on that type says inserting a key and value does not keep the key alive, even if the value references the key, and the entry is removed when the key dies. The delegate, closure included, then lives exactly as long as the subscriber. ## The trade-offs a weak event brings - **Nondeterminism.** A closed window that has not been collected yet still receives events and runs its handler, possibly against torn-down state. Weak does not mean "unsubscribed on close". - **Cost.** Each raise checks weak references, prunes, and invokes through reflection or an extra delegate; weak handles also add work for the collector. - **Silent loss.** A bug in what is held weakly shows up as a handler that stops firing, which is harder to notice than a leak. - **Still needs pruning.** The list of weak entries itself grows unless dead entries are removed. Because of these costs, weak events are best reserved for publishers that genuinely cannot know their subscribers' lifetimes, such as framework-level services; when a subscriber has a clear end of life, an explicit `-=` stays simpler and deterministic. ## A checklist for a hand-written weak event 1. Store `WeakReference<object>` to `handler.Target` and the `handler.Method`, never a weak reference to the delegate itself. 2. Decide what to do with a `null` `Target` (a static method): hold that delegate strongly, since there is no subscriber to leak. 3. Decide what to do with closures: reject them, or keep them alive through a `ConditionalWeakTable<TKey,TValue>` keyed on the subscriber. 4. Prune dead entries on raise (or on subscribe) so the list does not grow without bound. 5. Copy the live entries before invoking, so a handler that subscribes or unsubscribes during the raise does not disturb the loop. 6. Keep an explicit unsubscribe, so subscribers with a known end of life still detach deterministically.

  • How does ConditionalWeakTable<TKey,TValue> let a weak event accept lambda handlers?
    Key the table on the subscriber and store the delegate as the value. The table keeps a value alive only while its key is alive and does not keep the key alive, even when the value references it, so the closure lives exactly as long as the subscriber. The publisher can then hold the delegate weakly without the closure being collected early.
  • Why might a handler on a weak event run against a window that has already been closed?
    Closing a window does not collect it. Until the next garbage collection actually frees the window, `TryGetTarget` still succeeds and the publisher still invokes its handler. Handlers on weak events therefore need to check their own closed or disposed state, or the window should still unsubscribe explicitly when it closes.

  • Wrapping the handler delegate in WeakReference<T> makes the subscriber collectable.
  • A weak event unsubscribes a window as soon as the window closes.
  • Weak events work the same for lambdas, method groups and static methods.
  • WeakReference<T> releases its target after the first successful TryGetTarget call.
  • Weak events cost nothing compared with a field-like event.