Events: The Notice Board

Events: The Notice Board in C#: The building manager who needs to tell forty flats that the water is off has two options.

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 writesPublic delegate fieldevent
sensor.ReadingTaken += LogAllowedAllowed
sensor.ReadingTaken -= LogAllowedAllowed
sensor.ReadingTaken = LogAllowed — wipes every other subscriberCompile error
sensor.ReadingTaken(this, e)Allowed — anyone can forge a noticeCompile error
sensor.ReadingTaken = nullAllowed — silently unsubscribes everyoneCompile 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 — -= in Dispose, 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

MechanismFits whenWatch out for
eventZero or many in-process listeners, fire and forgetLeaks, synchronous handlers, exceptions
Func/Action parameterExactly one callback, and you want its resultNot multicast, no unsubscribe
IProgress<T>Reporting progress out of async workOne consumer, marshals to the captured context
IObservable<T> / RxStreams you compose, filter and throttleA dependency and a learning curve
Channel<T>Producer and consumer at different speedsYou must drain it; bound the capacity
Message busAcross processes or servicesSerialization, 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

  1. 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.
  2. 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.
  3. Using if (E != null) E(...). A subscriber unsubscribing between the check and the call turns it into a NullReferenceException. Always E?.Invoke(...).
  4. Exposing a public delegate field instead of an event. Any caller can then raise it, or wipe every subscriber with a single =.
  5. Letting a subscriber's exception escape the raiser. It kills the remaining handlers and surfaces as a publisher bug. Walk GetInvocationList when subscribers are untrusted.
  6. Reading a return value from a multicast event. Only the last handler's value survives. Events return void; use a Func<T> when you need an answer.
  7. Writing async void handlers. Nothing can await them and an unhandled exception tears down the process. Keep the handler synchronous, or hand the work to a queue.
  8. 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>, a protected virtual OnXxx raiser, and EventArgs.Empty when there is nothing to report.
  • Name events for what happened, in the tense that matters — Saving before, Saved after — so subscribers know whether they can still influence the outcome.
  • Pair every += with a -= in the subscriber's teardown, and implement IDisposable if 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 GetInvocationList and a try/catch per handler when the publisher must survive them.
  • Reach for IProgress<T> inside async work and Channel<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

  1. Give Sensor a second event Calibrated using the non-generic EventHandler, raise it with EventArgs.Empty, and subscribe two handlers to show the invocation order.
  2. Write a Countdown class that raises Tick for each second and Elapsed at zero. Subscribe with a stored lambda, unsubscribe halfway through, and print enough to prove the change took effect.
  3. Convert a class that exposes public Action<string>? OnMessage into a proper event, then list every call in your test code that stops compiling and why each one was a hazard.
  4. Build a Publisher with a static event and a Subscriber that never unsubscribes. Create 10,000 subscribers, force a collection with GC.Collect(), and use a counter in a finalizer to show that none were reclaimed. Then fix it and re-run.