Skip to content
Tutorials Center
My learning

Topics

Lesson 76 of 182 ยท Delegates, Events and LINQ

Events

Learn C# events step by step - the event keyword, EventHandler<T>, event args, subscribing and unsubscribing, memory leaks, thread-safety and weak event ideas.

A button knows when it was clicked, but it should not know what happens next. A download manager knows when a file finishes, but it should not know whether the app wants to show a notification, update a progress bar, or write a log line. The publisher/subscriber idea solves this: one object announces "something happened", and any number of other objects can listen without the publisher knowing who they are.

In C# this is built into the language as events. An event is a delegate wrapped in a safety layer: outsiders may subscribe and unsubscribe, but only the owner can raise it. This lesson builds events from the ground up, shows the standard EventHandler<T> pattern, and then covers the things professionals worry about: unsubscribing, memory leaks, exceptions in handlers and threads.

Why not just a public delegate field?

You could expose a plain delegate and let others add handlers to it. Let's see what goes wrong:

C# A public delegate field is too open

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The first Ring() calls both handlers. After the assignment =, handlers A and B are gone (the second Ring() prints only "Hijacked!"): any code could wipe out other subscribers. Any code could also invoke OnRing itself, as the last line does, pretending the alarm rang. Both are bugs waiting to happen.

The event keyword

Adding the event keyword to the same field removes both problems. Outside the declaring class, you can only use += and -=:

C# The same alarm with the event keyword

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Inside Alarm the name Rang still behaves like a delegate, so Rang?.Invoke() works. The ?. matters: if nobody subscribed, the event is null, and calling it directly would throw a NullReferenceException. The nullable annotation Action? is honest about this.

An event is to a delegate what a property is to a field. The event keyword generates hidden add and remove accessors, and the compiler only lets outsiders call those two.

The standard pattern: EventHandler and EventArgs

You can use any delegate type for an event, but the .NET libraries follow one convention that every C# developer recognizes:

  • The delegate takes two parameters: object? sender (who raised it) and an event-data object.
  • The event data is a class that inherits EventArgs, or is any type when you use the generic EventHandler<TEventArgs>.
  • The raising code lives in a protected virtual void OnSomething(...) method.

Since .NET Core the generic version does not require TEventArgs to derive from EventArgs, so a record is a neat way to carry the data:

C# EventHandler of T with a record as the event data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Why the OnProgress helper? A subclass can override it to run extra logic before or after the event, and the null check lives in one place. Passing this as the sender lets one handler method serve several publishers and still know which one fired.

Event names are usually verbs: Clicked, Completed, PropertyChanged. Past tense (Closed) means it already happened; present participle (Closing) means it is about to happen and handlers may cancel it (see below).

Subscribing with methods, lambdas and unsubscribing

Handlers can be named methods or lambdas. Methods are easier to unsubscribe, because -= needs the same delegate:

C# Subscribe and unsubscribe

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The last two lines are a classic trap. Two lambdas with identical text are two different delegate objects, so the -= removes nothing and the first lambda keeps firing ("Lambda sees 30" is printed). If you need to unsubscribe later, store the lambda in a variable first, or use a named method.

Removing a handler that was never added is silently ignored, which is why -= in cleanup code is safe.

Events that can be cancelled

Sometimes handlers should be able to say "stop". The classic approach is an event-args object with a settable property. The publisher raises the event first and then reads the answer:

C# A cancellable Closing event

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Notice that the same args object travels through every handler, so with several subscribers any one of them can set Cancel. If you design this pattern, decide whether the last writer wins or whether any true should stick.

Memory leaks: the forgotten subscription

A subscription is a reference from the publisher to the subscriber. The publisher's delegate list holds the subscriber's method, which holds the subscriber object. If the publisher lives for the whole program (a static event, a singleton, a main window) and a short-lived subscriber never unsubscribes, the garbage collector can never free that subscriber. This is one of the most common memory leaks in .NET applications.

You can prove it with a WeakReference, which observes an object without keeping it alive:

C# A subscriber that cannot be collected

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The listener that unsubscribed was collected, but the one that forgot is still reachable through bus. (The helper method is marked NoInlining so that no local variable accidentally keeps the listener alive in an optimized build; garbage collection demos are fragile, so treat this as an illustration of the rule, not a benchmark.)

Rules of thumb:

  • If the publisher lives no longer than the subscriber, you do not need to unsubscribe.
  • If the publisher lives longer, make unsubscribing part of the subscriber's lifetime: implement IDisposable and use -= in Dispose.
  • Be extra careful with static events: they live for the whole process.

A weak event pattern stores the subscriber through a WeakReference so the publisher does not keep it alive. .NET has built-in versions in WPF (WeakEventManager), but the idea is simple and you rarely need to write it yourself: prefer explicit unsubscribing, or use the subscriber's own IDisposable.

What happens when a handler throws?

Raising an event simply calls the multicast delegate. Handlers run one after another on the same thread, in subscription order. If one throws, the exception propagates out of Invoke and the remaining handlers never run:

C# One bad handler stops the others

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

GetInvocationList() returns the individual handlers so the publisher can call them one by one and decide what a failure means. Whether to isolate handlers is a design choice: a UI framework usually does not, a logging or analytics bus often does.

Thread-safety notes

Two separate problems exist.

Raising while someone unsubscribes. The old advice was to copy the delegate to a local variable before checking for null. Today, Happened?.Invoke(...) does that for you: it reads the field once, so another thread setting it to null between a check and a call cannot cause a NullReferenceException. Delegates are immutable, so a handler removed after the read may still be called once more. Your handlers must tolerate that.

Handlers run on the raising thread. If a background thread raises the event, subscribers execute on the background thread. A handler that touches a UI control must marshal back to the UI thread (in WPF/WinForms/MAUI with the dispatcher, in server apps usually it just does not matter). The compiler-generated add/remove accessors for a field-like event are thread-safe; they use a lock-free compare-and-swap loop internally.

Do not raise events while holding a lock. A handler might call back into your object or take another lock, and you get deadlocks. Collect the data under the lock, release it, then raise.

Custom add and remove accessors

You can write the accessors yourself, for example to store handlers in a dictionary so that a class with many events does not pay for one field per event:

C# Custom event accessors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Custom accessors are rare in application code. You will meet them in framework classes that keep a shared table of handlers. If you write them, you take over thread-safety yourself.

Events or delegates or interfaces?

  • Use an event when the publisher announces facts to any number of unknown listeners (zero is fine).
  • Use a delegate parameter or property when exactly one piece of behavior is required for one call (a sort comparison, a retry callback).
  • Use an interface when the callee needs several related operations.
  • For asynchronous notification streams over time, look at IObservable<T> (Rx) or Channel<T> instead of events; async handlers (async void) hide exceptions and are best avoided outside UI event handlers.

Events are the basis of the observer pattern, which you will meet again in Design Patterns in C#.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the event keyword prevent outside the declaring class?

    Outside the class you can only use += and -=. Assignment and direct invocation are compile errors (CS0070), so no one can wipe out other subscribers or fake the event.
  2. 2. Why is Happened?.Invoke(this, e) preferred over if (Happened != null) Happened(this, e)?

    The null-conditional operator evaluates the event field once. The old two-step check could see non-null and then call a field another thread had just set to null.
  3. 3. You write x.Changed += (s, e) => Log(); and later x.Changed -= (s, e) => Log();. What happens?

    Delegate equality compares the target and method, and each lambda expression creates its own. Keep the delegate in a variable, or use a named method, if you need to unsubscribe.
  4. 4. A short-lived object subscribes to an event on a long-lived singleton and never unsubscribes. What is the likely consequence?

    The publisher's invocation list references the subscriber, keeping it alive as long as the publisher lives. Unsubscribe in Dispose, or use a weak event.
  5. 5. Three handlers are subscribed and the second throws. What happens to the third when the event is raised with Invoke?

    Handlers are called sequentially on the same thread. An unhandled exception stops the chain unless the publisher calls GetInvocationList() and wraps each call in try/catch.

Summary

  • An event is a delegate with restricted access: outsiders can only subscribe (+=) and unsubscribe (-=); only the declaring class can raise it.
  • Follow the standard pattern: event EventHandler<TArgs>? Name, a protected virtual void OnName(TArgs e) raiser, sender as the first parameter and event data as the second.
  • Raise with Name?.Invoke(this, args) so that zero subscribers and concurrent unsubscribes are safe.
  • Lambdas cannot be removed by repeating them; keep a reference or use a named method.
  • A subscription keeps the subscriber alive: unsubscribe when the publisher outlives the subscriber, especially for static events.
  • Handlers run in order on the raising thread; a thrown exception stops the remaining handlers unless you use GetInvocationList().
  • Cancellable events use a settable property on the event-args object.

Next: LINQ Basics