Skip to content

Events and Callbacks

The Course
•
25 min study

A library shouldn't print to the console, or know what its callers want to do when something happens. It should announce what happened and let them decide. Today's lessons cover how to design those boundaries, starting with the simplest: events.

event

An event is a list of delegates, with restrictions. Outside code can only add (+=) or remove (-=) its own handler, and only the owning class can raise it. Raising calls each handler in turn. ?.Invoke handles the case with no listeners, since an event with none is null. .NET's own events usually use EventHandler<TEventArgs>, a delegate taking (object? sender, TEventArgs e), so a handler can tell which object raised it. This lesson uses Action<T>, which is simpler when you own both sides; follow the EventHandler convention in a library others will consume.

One event, two listeners C#
#nullable enable

var counter = new Counter();
counter.Changed += value => Console.WriteLine($"first: {value}");
counter.Changed += value => Console.WriteLine($"second: {value}");

counter.Increment();

new Counter().Increment();
Console.WriteLine("no listeners, no problem");

class Counter
{
    private int value;

    public event Action<int>? Changed;

    public void Increment()
    {
        value++;
        Changed?.Invoke(value);
    }
}
Check your prediction
Text
first: 1
second: 1
no listeners, no problem

Try counter.Changed = null; from outside. It's a compile error, which is the difference between an event and a plain delegate field.

Handlers are part of your call

Handlers run on the raiser's thread, inside its method, in order. A slow one holds everything up. An exception from one stops the rest, and it reaches the code that raised the event. Consider that before you raise an event in the middle of an operation.

A failing handler C#
#nullable enable

var source = new Source();
source.Happened += () => Console.WriteLine("first");
source.Happened += () => throw new InvalidOperationException("handler failed");
source.Happened += () => Console.WriteLine("third");

try
{
    source.Raise();
}
catch (InvalidOperationException e)
{
    Console.WriteLine(e.Message);
}

class Source
{
    public event Action? Happened;

    public void Raise()
    {
        Happened?.Invoke();
    }
}
Check your prediction
Text
first
handler failed

The leak

A long-lived object holding an event keeps every subscriber alive, because the delegate references them. Forget -= and those objects are never collected. It's a classic .NET memory leak. Returning an IDisposable makes unsubscribing hard to forget. A lambda can't be removed with -= unless it's stored, and this design takes care of that as well.

A subscription you can dispose C#
var bus = new Bus();
using (bus.Subscribe(text => Console.WriteLine($"got {text}")))
{
    bus.Publish("a");
}
bus.Publish("b");
Console.WriteLine(bus.Listeners);

class Bus
{
    private readonly List<Action<string>> handlers = new();

    public int Listeners => handlers.Count;

    public IDisposable Subscribe(Action<string> handler)
    {
        handlers.Add(handler);
        return new Subscription(() => handlers.Remove(handler));
    }

    public void Publish(string text)
    {
        foreach (Action<string> handler in handlers.ToArray())
        {
            handler(text);
        }
    }

    private sealed class Subscription(Action remove) : IDisposable
    {
        public void Dispose() => remove();
    }
}
Check your prediction
Text
got a
0

ToArray protects the loop if a handler unsubscribes during the call. Otherwise, the list would change while it's being looped over, and that throws.

IProgress for long operations

Long tasks often need to report progress. IProgress<T> is the standard interface. A long operation takes one as an optional parameter and calls Report. Progress<T> is the usual implementation, and it posts each call to the UI thread in a desktop app. Its callback runs later, so a tiny custom class is better in tests. Here's one.

Report as you go C#
#nullable enable

var reports = new List<int>();
await ProcessAsync(3, new Recorder(reports));
Console.WriteLine(string.Join(",", reports));

await ProcessAsync(1);
Console.WriteLine("works with none");

static async Task ProcessAsync(int items, IProgress<int>? progress = null)
{
    for (int i = 1; i <= items; i++)
    {
        await Task.Yield();
        progress?.Report(i * 100 / items);
    }
}

class Recorder(List<int> reports) : IProgress<int>
{
    public void Report(int value) => reports.Add(value);
}
Check your prediction
Text
33,66,100
works with none

Choosing a shape

You needUse
Several listeners, optionalAn event
Exactly one required stepAn interface or Func parameter
Progress updates for a callIProgress<T>
A stream of results for the caller to pullIAsyncEnumerable<T>

Runner.RunAsync returns a stream because the caller needs every outcome, at its own pace, with backpressure. An event would give no way to slow the source down.

Your turn

Exercise

A store with change notifications

Write Store<TKey, TValue> with Set(key, value) and TryGet. It has an event Changed of type Action<Change<TKey, TValue>>, where the record Change holds the key, old value and new value. Set only raises the event when the value really changes. If a handler throws, the value must stay set, and every other handler must still run. Afterwards, the exceptions reach the caller as an AggregateException.

Attach a handler that prints each change and another that throws for key bad. Print what happens as you set a=1, a=1 again, a=2, and bad=1, then show that bad was stored. Use GetInvocationList() to call handlers one at a time. A new key has no old value, so pass default as Old; for int that prints as 0.

When it works, it prints:

Text
a: 0 -> 1
third handler ran
a: 1 -> 2
third handler ran
bad: 0 -> 1
third handler ran
handler refused
True
Your workspace C#
#nullable enable

Action<int>? handlers = null;
handlers += value => Console.WriteLine(value);
Console.WriteLine(handlers.GetInvocationList().Length);
Hint 1: the idea

Store the value first. Then raising the event can't undo that. Loop over the handlers yourself, catching and remembering each exception, and throw them together at the end.

Hint 2: a first step

EqualityComparer<TValue>.Default.Equals compares values generically. Each item in GetInvocationList() is a Delegate, and a cast gives you back something you can call.

Show one solution
C#
#nullable enable

var store = new Store<string, int>();
store.Changed += change => Console.WriteLine($"{change.Key}: {change.Old} -> {change.New}");
store.Changed += change =>
{
    if (change.Key == "bad")
    {
        throw new InvalidOperationException("handler refused");
    }
};
store.Changed += change => Console.WriteLine("third handler ran");

store.Set("a", 1);
store.Set("a", 1);
store.Set("a", 2);

try
{
    store.Set("bad", 1);
}
catch (AggregateException e)
{
    Console.WriteLine(e.InnerExceptions[0].Message);
}
Console.WriteLine(store.TryGet("bad", out int stored) && stored == 1);

record Change<TKey, TValue>(TKey Key, TValue? Old, TValue New);

class Store<TKey, TValue> where TKey : notnull
{
    private readonly Dictionary<TKey, TValue> values = new();

    public event Action<Change<TKey, TValue>>? Changed;

    public bool TryGet(TKey key, out TValue? value) => values.TryGetValue(key, out value);

    public void Set(TKey key, TValue value)
    {
        bool existed = values.TryGetValue(key, out TValue? old);
        if (existed && EqualityComparer<TValue>.Default.Equals(old, value))
        {
            return;
        }
        values[key] = value;

        var errors = new List<Exception>();
        foreach (Delegate handler in Changed?.GetInvocationList() ?? Array.Empty<Delegate>())
        {
            try
            {
                ((Action<Change<TKey, TValue>>)handler)(new Change<TKey, TValue>(key, old, value));
            }
            catch (Exception e)
            {
                errors.Add(e);
            }
        }
        if (errors.Count > 0)
        {
            throw new AggregateException(errors);
        }
    }
}
Text
a: 0 -> 1
third handler ran
a: 1 -> 2
third handler ran
bad: 0 -> 1
third handler ran
handler refused
True

a: 0 -> 1 is the honest cost of TValue? Old on an unconstrained TValue: for a reference type the ? allows null, but for int it is still plain int, so a new key's Old is 0 and looks like a real old value. If a listener must tell "added" from "was 0", give Change a bool Existed field, which Set already knows.

Handlers are called one at a time through GetInvocationList(), each inside its own try, so one that throws can't stop the others. The value is stored before any handler runs, and the collected exceptions are thrown together at the end.

Was this article helpful?

Your response is saved on this device.