The Analogy: The Board in the Lobby
The building manager who needs to tell forty flats that the water is off has two options. Knock on forty doors — which means keeping a list of who lives where, noticing when someone moves out, and doing it all again next week. Or pin one notice to the board in the lobby and let whoever cares read it.
The board is the better design for a reason worth naming: the manager no longer knows or cares who is reading. Residents come and go, a new tenant starts checking the board, someone stops bothering, and not a line of the manager's routine changes. The notice is the same notice regardless of the audience.
An event is that board. A Sensor that raises ReadingTaken has no reference to the logger, the alarm or the chart that respond to it — it pins a notice and moves on. Each of those subscribers attached itself, can detach itself, and can fail without the sensor knowing. The coupling runs one way only: subscribers know about the publisher, the publisher knows about nobody.
That inversion is what makes events worth the ceremony. It is also where their two classic bugs live, both of which the analogy predicts: a notice pinned to a board nobody is watching does nothing at all, and a resident who moves out without taking their subscription down stays on the manager's list forever.
Syntax or Core Structure
An event is a delegate field with a lock on the front door: subscribers may add and remove, and only the declaring type may raise it.
using System;
// The notice itself: everything a subscriber is told.
class ReadingEventArgs : EventArgs
{
public int Celsius { get; }
public ReadingEventArgs(int celsius) => Celsius = celsius;
}
class Sensor
{
// The board. Outside code can only += and -=.
public event EventHandler<ReadingEventArgs>? ReadingTaken;
public void Take(int celsius) =>
ReadingTaken?.Invoke(this, new ReadingEventArgs(celsius));
}
class Program
{
static void Log(object? sender, ReadingEventArgs e) =>
Console.WriteLine("log: " + e.Celsius);
static void Main()
{
var sensor = new Sensor();
sensor.Take(18); // nobody watching: nothing happens
sensor.ReadingTaken += Log;
sensor.ReadingTaken += (s, e) =>
{
if (e.Celsius > 30) Console.WriteLine("ALARM " + e.Celsius);
};
sensor.Take(21);
sensor.Take(35);
sensor.ReadingTaken -= Log; // a named method can be removed
sensor.Take(31);
}
}
Output:
log: 21
log: 35
ALARM 35
ALARM 31
Take(18) printed nothing, and that is the correct behaviour rather than a bug: ?.Invoke on an event with no subscribers is a no-op, which is why an unsubscribed event is silent instead of throwing. Handlers then ran in subscription order — Log before the alarm lambda — and after -= Log the alarm carried on alone.
Technical Depth: What event Adds to a Delegate
The lock on the front door
Drop the event keyword and ReadingTaken becomes an ordinary public delegate field. Everything still compiles, and three new abuses become possible:
| Outside code writes | Public delegate field | event |
|---|---|---|
sensor.ReadingTaken += Log | Allowed | Allowed |
sensor.ReadingTaken -= Log | Allowed | Allowed |
sensor.ReadingTaken = Log | Allowed — wipes every other subscriber | Compile error |
sensor.ReadingTaken(this, e) | Allowed — anyone can forge a notice | Compile error |
sensor.ReadingTaken = null | Allowed — silently unsubscribes everyone | Compile error |
event is that guarantee and nothing more. The compiler generates a private delegate field plus add and remove accessors, and you can write those accessors yourself when you need to store subscriptions elsewhere — a sparse control with hundreds of rarely-used events keeps them in a dictionary rather than paying for a field each.
Multicast, and the subscriber that throws
A delegate holding several handlers invokes them in order, on the calling thread, synchronously. If the third of five throws, the fourth and fifth never run, and the exception surfaces inside the publisher's Invoke — the publisher gets blamed for a subscriber's bug. Isolating them means walking the list yourself:
foreach (Delegate handler in Progress?.GetInvocationList() ?? Array.Empty<Delegate>())
{
try { ((EventHandler<ProgressEventArgs>)handler)(this, e); }
catch (Exception ex) { Log(ex); } // one bad listener, not a dead pipeline
}
Return values behave badly for the same reason: with several handlers only the last one's value survives, which is why event delegates return void by convention. When you genuinely want an answer back, pass a Func<T> instead of raising an event.
Why ?.Invoke and not an if
// Racy: a subscriber can unsubscribe between the check and the call.
if (ReadingTaken != null) ReadingTaken(this, e);
// Safe: ?. reads the field once into a temporary, then calls that.
ReadingTaken?.Invoke(this, e);
Delegates are immutable, so -= replaces the field rather than editing a list. The null-conditional form therefore invokes the snapshot it read, which may include a handler that has just unsubscribed — unavoidable, and far better than the NullReferenceException the if version throws. The compiler-generated add and remove accessors are themselves thread-safe, so concurrent += calls never lose a subscriber.
The leak nobody sees
An event is a strong reference from publisher to subscriber. A long-lived publisher plus a short-lived subscriber that never unsubscribes is a memory leak with no visible symptom:
// The static clock keeps every window alive forever.
Clock.Tick += window.Refresh;
The window is closed, its screen is gone, and it is still in memory being ticked sixty times a second, because Clock holds its handler. The rules that avoid it:
- Unsubscribe in the same place you dispose —
-=inDispose,OnUnload, or wherever the subscriber's life ends. - Store the delegate if you subscribed with a lambda, because
-=needs the same instance.x.E += (s, e) => F();can never be removed; a lambda captured in a field can. - Prefer the subscriber outliving the publisher when you get to choose the direction. A short-lived publisher leaks nothing.
Events, and the alternatives
| Mechanism | Fits when | Watch out for |
|---|---|---|
event | Zero or many in-process listeners, fire and forget | Leaks, synchronous handlers, exceptions |
Func/Action parameter | Exactly one callback, and you want its result | Not multicast, no unsubscribe |
IProgress<T> | Reporting progress out of async work | One consumer, marshals to the captured context |
IObservable<T> / Rx | Streams you compose, filter and throttle | A dependency and a learning curve |
Channel<T> | Producer and consumer at different speeds | You must drain it; bound the capacity |
| Message bus | Across processes or services | Serialization, delivery guarantees, ops |
Events are also awkwardly synchronous in an async world. An async void handler cannot be awaited and its exceptions crash the process, so the publisher has no idea whether the work finished. For anything genuinely asynchronous, Channel<T> or an explicit Func<T, Task> list is the honest tool.
Real World Example: An Importer That Reports Progress
A long-running import needs to tell a UI, a log and a metrics counter how far it has got, without knowing that any of them exist. One publisher, two events, and a subscriber that misbehaves on purpose.
using System;
using System.Collections.Generic;
class ImportProgressEventArgs : EventArgs
{
public int Done { get; }
public int Total { get; }
public ImportProgressEventArgs(int done, int total)
{
Done = done;
Total = total;
}
public int Percent => Done * 100 / Total;
}
class Importer
{
public event EventHandler<ImportProgressEventArgs>? Progress;
public event EventHandler? Finished;
// The standard raiser: protected virtual, so subclasses can extend it.
protected virtual void OnProgress(ImportProgressEventArgs e)
{
// One broken subscriber must not stop the others.
foreach (Delegate handler in Progress?.GetInvocationList() ?? Array.Empty<Delegate>())
{
try
{
((EventHandler<ImportProgressEventArgs>)handler)(this, e);
}
catch (Exception ex)
{
Console.WriteLine("subscriber failed: " + ex.GetType().Name);
}
}
}
public void Run(IReadOnlyList<string> rows)
{
for (int i = 0; i < rows.Count; i++)
OnProgress(new ImportProgressEventArgs(i + 1, rows.Count));
Finished?.Invoke(this, EventArgs.Empty);
}
}
class Program
{
static void Main()
{
var importer = new Importer();
// Held in a variable, so it can be unsubscribed later.
EventHandler<ImportProgressEventArgs> bar = (s, e) =>
Console.WriteLine("progress " + e.Percent + "%");
importer.Progress += bar;
importer.Progress += (s, e) =>
{
if (e.Done == 2) throw new InvalidOperationException("bad row");
};
importer.Finished += (s, e) => Console.WriteLine("finished");
importer.Run(new[] { "a", "b", "c", "d" });
importer.Progress -= bar; // what subscribes, unsubscribes
Console.WriteLine("--- after unsubscribe ---");
importer.Run(new[] { "x", "y" });
}
}
Output:
progress 25%
progress 50%
subscriber failed: InvalidOperationException
progress 75%
progress 100%
finished
--- after unsubscribe ---
subscriber failed: InvalidOperationException
finished
The important line is progress 75%. A subscriber threw on row 2 and the import carried on to 100% and finished — with a bare Progress?.Invoke(this, e) that exception would have escaped Run, abandoned rows 3 and 4, and looked exactly like a bug in the importer. Walking GetInvocationList turns a subscriber's fault into a logged line, which is the right blame allocation for a notice board: a resident who cannot read is not the manager's problem.
The unsubscribe half shows why the lambda was hoisted into bar. -= bar removes precisely the handler that += bar added, because it is the same delegate instance. The thrower, written inline, is unremovable — it is still attached on the second run, still failing on row 2. Every += with an inline lambda on a publisher that outlives the subscriber is a leak you have no handle to fix.
Common Mistakes
- Subscribing with an inline lambda and expecting to unsubscribe.
-=compares delegate instances, and a second lambda with identical code is a different instance. Store it in a field or use a named method. - Never unsubscribing from a long-lived publisher. A static or singleton event keeps every handler's target alive. This is the most common managed memory leak in .NET UI code.
- Using
if (E != null) E(...). A subscriber unsubscribing between the check and the call turns it into aNullReferenceException. AlwaysE?.Invoke(...). - Exposing a public delegate field instead of an event. Any caller can then raise it, or wipe every subscriber with a single
=. - Letting a subscriber's exception escape the raiser. It kills the remaining handlers and surfaces as a publisher bug. Walk
GetInvocationListwhen subscribers are untrusted. - Reading a return value from a multicast event. Only the last handler's value survives. Events return
void; use aFunc<T>when you need an answer. - Writing
async voidhandlers. Nothing can await them and an unhandled exception tears down the process. Keep the handler synchronous, or hand the work to a queue. - Assuming handlers run somewhere else. Raising an event is a plain synchronous call on the current thread, so a slow subscriber blocks the publisher — including the UI thread.
Best Practices
- Follow the framework shape:
EventHandler<TEventArgs>, aprotected virtual OnXxxraiser, andEventArgs.Emptywhen there is nothing to report. - Name events for what happened, in the tense that matters —
Savingbefore,Savedafter — so subscribers know whether they can still influence the outcome. - Pair every
+=with a-=in the subscriber's teardown, and implementIDisposableif that is the only place to put it. - Keep the payload immutable and self-contained: get-only properties on the args, no live reference to the publisher's mutable internals.
- Do the least possible work in a handler. Capture what you need, queue the rest, and never block a publisher you do not own.
- Isolate untrusted subscribers with
GetInvocationListand atry/catchper handler when the publisher must survive them. - Reach for
IProgress<T>inside async work andChannel<T>for producer-consumer pipelines; events are for in-process, fire-and-forget notification. - Raise from one place only. A single raiser method means one null check, one isolation policy, and one place to add logging.
Practice Exercises
- Give
Sensora second eventCalibratedusing the non-genericEventHandler, raise it withEventArgs.Empty, and subscribe two handlers to show the invocation order. - Write a
Countdownclass that raisesTickfor each second andElapsedat zero. Subscribe with a stored lambda, unsubscribe halfway through, and print enough to prove the change took effect. - Convert a class that exposes
public Action<string>? OnMessageinto a proper event, then list every call in your test code that stops compiling and why each one was a hazard. - Build a
Publisherwith a static event and aSubscriberthat never unsubscribes. Create 10,000 subscribers, force a collection withGC.Collect(), and use a counter in a finalizer to show that none were reclaimed. Then fix it and re-run.