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?
answer
- lifetime mismatch is the risk
- who owns the subscription
- IDisposable subscription objects
- weak events where lifetimes are unknown
- no static events for views
basics
~20 sMake 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.
solid answer
~40 sThere is no single right rule, but the default I would set is explicit ownership. Long-lived services do not expose raw `event` members to views; they offer `Subscribe(handler)` returning `IDisposable`, which captures the exact delegate it added, so the removal always matches and a view disposes its subscriptions with itself. Short-lived publishers and objects a view owns may keep plain events. Static events are banned for anything a view subscribes to. Weak events are allowed only in shared infrastructure whose subscribers' lifetimes are unknowable, documented with their nondeterminism. The rule is backed by a review checklist and a leak test per view: open, close, collect, assert the `WeakReference<T>` is dead.
code
csharp · 37 linesvar settings = new SettingsService();
using (var window = new DocumentWindow(settings))
{
settings.Change("dark theme"); // window: dark theme
} // Dispose ends the subscription
settings.Change("large font"); // nobody listening
Console.WriteLine(settings.SubscriberCount); // 0
sealed class SettingsService
{
private event Action<string>? Changed;
public int SubscriberCount => Changed?.GetInvocationList().Length ?? 0;
public IDisposable Subscribe(Action<string> handler)
{
Changed += handler;
return new Subscription(() => Changed -= handler); // removes the very same instance
}
public void Change(string what) => Changed?.Invoke(what);
private sealed class Subscription(Action unsubscribe) : IDisposable
{
private Action? _unsubscribe = unsubscribe;
public void Dispose() => Interlocked.Exchange(ref _unsubscribe, null)?.Invoke();
}
}
sealed class DocumentWindow(SettingsService settings) : IDisposable
{
private readonly IDisposable _subscription =
settings.Subscribe(what => Console.WriteLine($"window: {what}"));
public void Dispose() => _subscription.Dispose();
}go deeper
Know the team rule you are asked to follow: dispose subscriptions to long-lived services when your view closes, and never unsubscribe with a new lambda.
Explain how a Subscribe method returning IDisposable guarantees the removal matches, and why static events are banned for view code.
Write the leak test that enforces the rule and spot subscriptions without an owner in review, including lambdas that capture views.
Weigh deterministic unsubscription, subscription objects and weak events against the codebase's publishers and plugin model, and choose where each failure mode is acceptable.
## What the lead is really deciding Handler leaks are not a bug in one class; they are a **lifetime mismatch** that the language does nothing to prevent. A field-like C# event keeps every subscriber's delegate, and so its `Target`, until someone calls `-=` with an equal delegate. In a large desktop codebase with dozens of views and a handful of app-lifetime services, "remember to unsubscribe" fails at scale. The lead's decision is which mechanism the team relies on so that forgetting is hard, and what that mechanism costs. ## The options and their trade-offs | Policy | Strength | Cost | |---|---|---| | Always `-=` in `Dispose` | Deterministic, no extra machinery | Relies on discipline; a fresh lambda at `-=` fails silently | | Subscription objects (`IDisposable`) | Removal always uses the exact delegate; ownership is visible | Every service API changes shape; owners must still dispose | | Weak events | A forgotten unsubscribe no longer leaks | Nondeterministic delivery to closed views, lambda pitfalls, per-raise cost | | No long-lived events at all | Removes the class of bug | Pushes notification into polling or messaging, with its own complexity | ## A defensible default 1. **Classify publishers by lifetime.** App-lifetime services, per-document objects, and objects a view owns. Only the first group needs a rule; an event on an object the view owns dies with the view. 2. **Long-lived services return subscriptions.** Instead of `public event EventHandler? Changed`, expose `IDisposable Subscribe(Action<string> handler)`. The service adds the handler and returns an object that removes *that instance*; `IObservable<T>.Subscribe` in the BCL uses the same shape. A view stores the returned objects and disposes them in its own `Dispose`. 3. **Ban static events for view-facing notifications.** A static event's field lives as long as its type is loaded, so one forgotten removal leaks for the life of the process. 4. **Allow weak events only in shared infrastructure** whose subscribers' lifetimes cannot be known, and document that handlers may run on closed but uncollected views. 5. **Ban inline lambdas at `-=`.** Any unsubscribe must use a method group, a stored delegate, or the subscription object. ## Enforcing it - **Review checklist:** every `+=` on a long-lived publisher has an owner and a matching teardown; no lambda is written a second time at `-=`. - **Leak tests:** for each view type, create and close it in a non-inlined helper that returns a `WeakReference<T>`, call `GC.Collect()`, and assert `TryGetTarget` returns false. This catches regressions without a profiler. - **Base classes or helpers:** a view base class that owns a collection of subscriptions and disposes them all on close removes per-view boilerplate. ## When to choose differently - A small app with few views and no shared services may be well served by plain `-=` in `Dispose` plus the leak test. - A plugin host whose services cannot know when plugins unload may justify weak events as the default, accepting nondeterminism. - A team already using a reactive library gets subscription objects for free; the rule then becomes "dispose every subscription". ## What the rule costs - **API churn.** Turning service events into `Subscribe` methods touches every caller once; plan it as a migration, starting with the services that the most views subscribe to. - **A second vocabulary.** Developers must learn when a plain event is still fine (an object the view owns) and when it is not, so the rule needs a one-paragraph explanation, not just a lint. - **Disposal discipline moves, it does not vanish.** Somebody must still dispose the subscription objects; a view base class that owns them concentrates that duty in one place, which is the real gain. The judgment is about where the team wants the failure mode: a deterministic leak caught by a test, a silent missed notification, or an API that makes ownership impossible to skip. Most leads choose the last for long-lived services and keep plain events everywhere else.
- Why would you prefer subscription objects over requiring -= in every view's Dispose?The subscription object captures the exact delegate the service added, so removal can never fail because someone wrote a second lambda. Ownership also becomes visible: a view holds `IDisposable` fields, and a review can check that each is disposed. With bare events, the matching `-=` is a separate line that reviewers must remember to look for.
- When would you accept weak events as the team default?When publishers cannot know when their subscribers end, for example a host that loads plugin views it does not control, and when a missed or late notification is cheaper than a leak. The team must then accept that closed but uncollected views still receive events, and handlers must check their own closed state.
- Leaks are solved by telling everyone to remember -= in Dispose.
- Weak events should be the default for every event in the codebase.
- Static events are fine because the service is a singleton anyway.
- Without a memory profiler there is no way to test for handler leaks.