Event lifetime and cleanup
Event lifetime and cleanup
An event subscription is a relationship with a lifetime. For a typical instance handler, a long-lived publisher can keep the subscriber reachable through its delegate. Detach when the subscriber no longer needs notifications; do not rely on garbage collection to end the relationship.
Examples target the proposed C# 14 / .NET 10 console baseline. Each is a separate Program.cs; expected outputs are reasoned, not executed.
Remove the same delegate
+= combines a handler with a field-like event; -= removes the last matching occurrence when present. A newly written lambda is not a reliable way to identify an earlier subscription. Keep the delegate or use a matching method group.
using System;var clock = new Clock();int count = 0;EventHandler handler = (_, _) => count++;clock.Tick += handler;clock.Fire();clock.Tick -= handler;clock.Fire();Console.WriteLine(count);class Clock{ public event EventHandler? Tick; public void Fire() => Tick?.Invoke(this, EventArgs.Empty);}Only the first Fire has a subscriber. Unsubscription does not undo work that already happened.
Expected output (reasoned, not executed):
1Tie subscriptions to ownership
A subscriber that owns a subscription can implement IDisposable and remove it when its lifetime ends. A using block disposes even on an exception. Make cleanup safe to repeat and avoid disposing objects the subscriber does not own.
using System;var feed = new Feed();using (var display = new Display(feed)){ feed.Refresh();}feed.Refresh();class Feed{ public event EventHandler? Updated; public void Refresh() => Updated?.Invoke(this, EventArgs.Empty);}class Display : IDisposable{ private readonly Feed feed; private bool disposed; public Display(Feed feed) { this.feed = feed; feed.Updated += OnUpdated; } private void OnUpdated(object? sender, EventArgs e) => Console.WriteLine("display updated"); public void Dispose() { if (disposed) return; disposed = true; feed.Updated -= OnUpdated; }}The second Refresh has no display listener. The display releases its subscription, not the shared feed.
Expected output (reasoned, not executed):
display updatedCustom accessors and duplicates
An event may supply explicit add and remove bodies. The compiler does not supply backing storage for such an event; here a private delegate stores subscriptions. This single-threaded teaching example preserves duplicate registration; production custom accessors need a concurrency policy.
using System;var meter = new Meter();EventHandler h = (_, _) => Console.WriteLine("read");meter.Changed += h;meter.Changed += h;meter.Changed -= h;meter.Signal();meter.Changed -= h;meter.Signal();class Meter{ private EventHandler? handlers; public event EventHandler Changed { add { handlers += value; } remove { handlers -= value; } } public void Signal() => handlers?.Invoke(this, EventArgs.Empty);}Two registrations minus one removal leave one handler. The second removal leaves none.
Expected output (reasoned, not executed):
readCommon mistakes and edge cases
Do not assume an event subscription is weak. In concurrent code, a handler captured in an invocation snapshot can still run after removal; disposal may need coordination beyond -=. Avoid locking around arbitrary handler execution. Weak-event patterns are platform-specific alternatives, not a replacement for clear ownership. A custom accessor must document duplicate and removal semantics.
Practice and recap
Subscribe one handler twice and another once, fire, remove the first handler once, fire again, then remove both remaining registrations and fire. Record the number of handler calls at each stage.
Hint: Removal deletes only one matching registration.
Learning objective: Remove subscriptions when ownership ends. See the accompanying manual practice and knowledge check.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Event lifetime and cleanup — knowledge check
Apply the lesson concepts to the following scenarios.
Why can a long-lived publisher retain a subscriber?
How reliably detach a previously registered lambda?
Two registrations of h and one -= h leave how many?
What should Display.Dispose release?
Can a concurrent callback still execute after unsubscribe?