Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

C# Event Subscription: Syntax, Pitfalls, and Clean Unsubscription

Learn C# event subscription syntax, why unsubscribing matters, how to avoid memory leaks, and when to use lambda, method group, or weak event patterns.

~6 min readC#
#C##events#delegates#memory leaks
Illustration of C# event subscription showing a publisher and subscriber connected by a delegate chain, with an emphasis on unsubscription to prevent memory leaks.

C# event subscription uses += to attach a handler to an event and -= to remove it. In real applications, knowing when and how to unsubscribe is just as important as the subscription syntax. A forgotten -= leaves the publisher holding a strong reference to the subscriber, which can cause memory leaks in long-running applications. This article covers the core operators, the pitfalls of anonymous methods and repeated subscriptions, the thread-safety behavior of events, and patterns for separating publisher and subscriber lifetimes.

Event Subscription Syntax: The += and -= Operators

The core of C# event subscription is the += operator, which attaches a handler method to an event. The -= operator removes it. Both operators work on the event's underlying delegate list. Here is a minimal example:

csharp
public class Button { public event EventHandler? Click; public void SimulateClick() { Click?.Invoke(this, EventArgs.Empty); } } public class Form { private readonly Button _button = new(); public Form() { _button.Click += OnButtonClick; } private void OnButtonClick(object? sender, EventArgs e) { Console.WriteLine("Button clicked"); } public void Detach() { _button.Click -= OnButtonClick; } }

+= and -= are the standard ways to add and remove handlers from outside the declaring class. The event keyword prevents external code from replacing the entire invocation list or invoking the event directly. For a field-like event, the compiler generates a backing delegate field and a pair of add and remove accessors; += and -= are translated to calls to those accessors, which use Delegate.Combine and Delegate.Remove internally.

Why Unsubscription Matters: Memory Leaks and Stale Handlers

If a subscriber never unsubscribes, the publisher holds a strong reference to the subscriber through the delegate. As long as the publisher is alive, the subscriber will not be garbage collected, even if no other references exist. This is a classic memory leak in event-driven applications.

Consider a window that subscribes to a static event:

csharp
public static class AppEvents { public static event EventHandler? UserLoggedIn; } public class Dashboard { public Dashboard() { AppEvents.UserLoggedIn += OnUserLoggedIn; } private void OnUserLoggedIn(object? sender, EventArgs e) { // Refresh UI } }

If a Dashboard instance is created and then closed, but the subscription is never removed, the static AppEvents class keeps a reference to the Dashboard instance. The instance stays in memory, and its finalizer (if any) never runs. Over time, this accumulates and can cause memory pressure or unexpected behavior because the handler still executes.

The fix is to unsubscribe in a deterministic place, such as a Dispose method or when the subscriber's lifetime ends. For instance:

csharp
public class Dashboard : IDisposable { public Dashboard() { AppEvents.UserLoggedIn += OnUserLoggedIn; } public void Dispose() { AppEvents.UserLoggedIn -= OnUserLoggedIn; } private void OnUserLoggedIn(object? sender, EventArgs e) { // Refresh UI } }

Always pair every += with a corresponding -= in the appropriate lifecycle method. This is not just a theoretical concern; it directly affects the memory footprint of desktop, server, and mobile applications.

Subscribing with Anonymous Methods and Lambda Expressions

Anonymous methods and lambda expressions are convenient for short-lived subscriptions, but they introduce a subtle problem: you cannot easily unsubscribe because you do not have a reference to the delegate instance.

csharp
button.Click += (sender, e) => Console.WriteLine("Clicked");

To unsubscribe, you must store the delegate in a local variable:

csharp
EventHandler handler = (sender, e) => Console.WriteLine("Clicked"); button.Click += handler; // Later button.Click -= handler;

If you subscribe with a lambda and never store it, you cannot remove that exact delegate. Even if you write the same lambda expression again, it creates a new delegate instance that is not equal to the one already subscribed. The only way to remove it is to store it.

This is especially dangerous in long-lived publishers. If you subscribe with a lambda inside a method that runs repeatedly, you accumulate multiple handlers. For example:

csharp
public void Refresh() { _button.Click += (sender, e) => HandleClick(); }

Each call to Refresh adds a new handler. The old handlers remain, so HandleClick runs multiple times. The solution is to either store the handler as a field or avoid subscribing in repeated methods.

Event Accessors: Custom add and remove Blocks

Sometimes you need to control what happens when a handler is added or removed. You can define custom event accessors instead of using the default field-like event. This is useful for logging, validation, or forwarding subscriptions to another object.

csharp
private EventHandler? _clickHandlers; public event EventHandler? Click { add { Console.WriteLine("Handler added"); _clickHandlers += value; } remove { Console.WriteLine("Handler removed"); _clickHandlers -= value; } }

Custom accessors also allow you to store handlers in a non-standard way, such as a List<EventHandler> or a weak reference collection. However, they do not change the subscription syntax; callers still use += and -=. The accessors give you full control over the underlying storage and side effects.

A common use case is to implement an event that only allows a single subscriber, or to add thread safety around the add/remove operations.

Thread Safety and Event Invocation

Field-like events are thread-safe in the sense that their compiler-generated add and remove accessors are synchronized, so concurrent += and -= calls will not corrupt the delegate chain. Custom event accessors are not automatically thread-safe. If you write custom add/remove blocks and multiple threads can subscribe or unsubscribe, you should synchronize access to the backing storage, for example with a lock:

csharp
private readonly object _eventLock = new(); private EventHandler? _clickHandlers; public event EventHandler? Click { add { lock (_eventLock) { _clickHandlers += value; } } remove { lock (_eventLock) { _clickHandlers -= value; } } }

Raising an event is a separate concern. When you raise an event, copy the delegate reference to a local variable before invoking it to avoid a NullReferenceException if another thread unsubscribes during invocation:

csharp
EventHandler? handler = Click; handler?.Invoke(this, EventArgs.Empty);

Even with this pattern, if a handler unsubscribes itself during the invocation, the copy still contains that handler, so it will be called. This is usually the desired behavior, but it means that unsubscription does not take effect until the next invocation.

Weak Event Pattern for Long-Lived Publishers

When a publisher has a longer lifetime than its subscribers, the strong reference held by the event prevents subscribers from being collected. The weak event pattern solves this by storing handler targets in weak references. When the subscriber is garbage collected, the weak reference becomes invalid, and the handler is not invoked.

WPF provides WeakEventManager, and some frameworks provide similar helpers, but the base class library does not include a universal weak event manager. A manual implementation must store both the delegate's method and a weak reference to its target. The following is a simplified example:

csharp
public class WeakEvent<TEventArgs> where TEventArgs : EventArgs { private readonly List<(WeakReference target, MethodInfo method)> _handlers = new(); public void AddHandler(EventHandler<TEventArgs> handler) { if (handler.Target == null) { throw new ArgumentException("Static handlers need a different implementation.", nameof(handler)); } _handlers.Add((new WeakReference(handler.Target), handler.Method)); } public void RemoveHandler(EventHandler<TEventArgs> handler) { _handlers.RemoveAll(h => h.target.Target == handler.Target && h.method == handler.Method); } public void Raise(object sender, TEventArgs e) { foreach (var (targetRef, method) in _handlers.ToList()) { var target = targetRef.Target; if (target == null) { _handlers.RemoveAll(h => h.target == targetRef && h.method == method); continue; } method.Invoke(target, new object[] { sender, e }); } } }

This is a simplified version; a production implementation must handle static handlers, clean up expired entries, and consider thread safety. The weak event pattern is most useful when you have a long-lived publisher and many short-lived subscribers, such as a global messaging service or a static event hub.

Common Pitfalls in Event Subscription

One common mistake is to let objects that are created and destroyed frequently subscribe to a long-lived event and never unsubscribe. For example, in a loop that creates new instances, each instance subscribes to a shared event. If the instance is not disposed, the shared event accumulates references.

Another pitfall is subscribing to events on static classes or singletons. Since the publisher never goes out of scope, the subscriber must explicitly unsubscribe. If the subscriber is also a singleton, the leak may not be noticeable, but if subscribers are transient, the memory grows.

A subtle issue arises when using method groups. If you subscribe with a method group and later try to unsubscribe with a different method group that points to the same method on the same instance, the delegate equality check works because the target and method are the same. However, if the method is an instance method and the instance is different, they are not equal. For lambdas and anonymous methods, store the delegate in a field or local variable so you can pass the same instance to -=.

Finally, be careful with event handlers that capture local variables in lambdas. The lambda captures the variable, not its value at subscription time. If the variable changes, the handler sees the latest value. This can lead to unexpected behavior if you expect the handler to use the value at the moment of subscription. Store the value in a local copy if needed.

Event subscription is a powerful tool, but it requires discipline. Always pair += with -=, store anonymous delegates if you need to remove them, and consider the lifetime of both publisher and subscriber. When in doubt, use the weak event pattern to decouple lifetimes.

Try matching browser tools

All tools

Small utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.

All C# guides

More in C#

All C# guides

The guides filed next to this one in C#, in library order.