Observer intent and structure, C# events and EventHandler<T>, IObservable<T>/IObserver<T> with IDisposable subscriptions and Rx, IOptionsMonitor<T>.OnChange and change tokens, INotifyPropertyChanged, unsubscribing and the leak risk, synchronous in-process notification vs broker-based pub/sub.
Observer is a one-to-many relationship: a subject keeps a list of observers and notifies them when something happens, without knowing their concrete types.
In .NET it's built into the language:
+= subscribes, -= unsubscribes, the publisher raises with Placed?.Invoke(this, e).IObservable<T>/IObserver<T>: Subscribe returns an IDisposable; disposing it unsubscribes. Rx.NET adds LINQ-style operators over these streams.IOptionsMonitor<T>.OnChange: notifies you when configuration reloads, and also returns an IDisposable you must dispose.Notification is synchronous and in-process, and the subject holds strong references to its observers, so forgotten subscriptions on a long-lived subject leak memory. For cross-process, durable notification you use pub/sub through a broker instead.
"Observer is when one object, the subject, needs to tell several others that something happened, without knowing who they are. The subject keeps a list of observers, observers register and unregister themselves, and when the subject's state changes it walks the list and calls each one. The point is loose coupling: the order service raises 'order placed' and doesn't need to know that loyalty points, email and analytics all care.
In C#, the language gives you this directly with events. An
event EventHandler<OrderPlaced>is the observer list;+=subscribes,-=unsubscribes, and the publisher raises it withPlaced?.Invoke(this, e), where the null-conditional handles the case of no subscribers. There's also theIObservable<T>andIObserver<T>pair:Subscribereturns anIDisposable, and disposing it is how you unsubscribe. Observers getOnNext,OnErrorandOnCompleted, so it models a stream that can fail or finish. Rx.NET builds LINQ-style operators likeThrottleandBufferon top. In ASP.NET Core the one I use most isIOptionsMonitor<T>.OnChange: whenappsettings.jsonor Azure App Configuration reloads, my callback runs with the new options. That also returns anIDisposable.The mistake I see is forgetting that the subject holds a strong reference to every observer. If a short-lived object subscribes to a singleton's event and never unsubscribes, the singleton keeps it alive forever, which is the classic .NET event leak. The other thing to remember is that notification is synchronous: one slow or throwing handler blocks or breaks the publisher. Observer is great for in-process notifications, but every subscription is a reference you've promised to release."
| Mechanism | Subscribe | Unsubscribe | Typical use |
|---|---|---|---|
C# event |
subject.Placed += handler |
subject.Placed -= handler |
Domain or UI notifications in-process |
IObservable<T> |
subject.Subscribe(observer) |
subscription.Dispose() |
Streams of values; Rx.NET pipelines |
IOptionsMonitor<T> |
monitor.OnChange(callback) |
subscription?.Dispose() |
Config reload, feature flags |
Others you'll meet: INotifyPropertyChanged (MVVM data binding), IChangeToken (configuration and file providers), CancellationToken.Register (notification on cancellation).
Observer (events, IObservable) |
Pub/sub via a broker (Service Bus, Event Grid) | |
|---|---|---|
| Where | Same process | Across processes and services |
| Coupling | Observers reference the subject | Publishers and subscribers only know the topic |
| Timing | Synchronous, immediate | Asynchronous; subscriber can be offline |
| Durability | Lost if the process dies | Messages persisted and retried |
| Failure | A throwing handler affects the publisher | Isolated per subscriber, with dead-lettering |
A pricing service used IOptionsMonitor<PricingOptions>.OnChange to refresh a cached rate table when Azure App Configuration changed, so rate updates went live in under 30 seconds without a redeploy. A later code review found the subscription wasn't disposed in a scoped class created per request; after about [two days] the process held several hundred thousand callbacks. Moving the subscription into a singleton fixed it.
Checks that the candidate recognises Observer in C# events and IObservable
Green flags
+=/-= and IDisposable subscriptions.IOptionsMonitor<T>.OnChange or change tokens.Red flags
Β«subjectΒ»
OrderBook
observers: list
Subscribe(o) / Unsubscribe(o)
Notify() ββ for each o: o.Update(e)
β
ββββββββββββΌββββββββββββ
βΌ βΌ βΌ
LoyaltyPoints EmailSender Analytics (Β«observerΒ»s)
The subject depends only on the observer abstraction (a delegate type or IObserver<T>), which is why new observers can be added without changing it.
A field-like event EventHandler<T>? Placed; compiles to a private delegate field plus add and remove accessors that combine and remove delegates with a thread-safe compare-exchange loop. The delegate is multicast: its invocation list holds each handler (target object plus method). Raising it calls each handler in order, synchronously, on the raising thread. If one handler throws, the remaining handlers don't run and the exception propagates to the publisher. Placed?.Invoke(this, e) reads the field once, so a handler removed concurrently can't cause a NullReferenceException.
Since .NET Framework 4.5, EventHandler<TEventArgs> no longer requires TEventArgs : EventArgs, so a record works as the payload.
IObservable<T> and IObserver<T>IObservable<T>.Subscribe(IObserver<T>) βββΆ IDisposable (the subscription)
IObserver<T>: OnNext(T) * (OnError(Exception) | OnCompleted())?
The grammar is: any number of OnNext calls, then at most one terminal call. This is the push dual of IEnumerable<T> (pull). Writing a correct observable by hand is fiddly (thread safety, the grammar, disposal during notification), so in practice you use Rx.NET (System.Reactive) or Subject<T> from it, which also gives operators like Where, Throttle, Buffer and ObserveOn.
IOptionsMonitor<T> and change tokensConfiguration providers expose an IChangeToken. With reloadOnChange: true (the default for appsettings.json in WebApplication.CreateBuilder), a file watcher fires the token, configuration reloads, and IOptionsMonitor<T> recomputes the options and calls each OnChange listener with the new value and the options name. OnChange returns an IDisposable?; dispose it when the listener's owner goes away. File watchers can raise more than one event for a single save, so listeners should be idempotent.
The subject holds a strong reference to each observer through the delegate's Target (or the observer list). If the subject lives longer than the observer, the observer can't be collected until it unsubscribes. Static events and singleton subjects are the usual culprits. Fixes: unsubscribe in Dispose, keep subscriptions in objects with the same lifetime as the subject, or use weak event patterns (WPF's WeakEventManager) where unsubscription can't be guaranteed.
async void handler escapes this, but its exceptions crash the process if unobserved.OrderBook with an event and two subscribers; make one throw and observe that the second doesn't run.IObservable<decimal> by hand, then replace it with Rx.NET's Subject<decimal> and add .Throttle.IOptionsMonitor<T>.OnChange, edit appsettings.json while the app runs, and count how many callbacks fire per save.dotnet-gcdump, and find who keeps the objects alive.Three forms of Observer in .NET: a C# event, IObservable<T>, and IOptionsMonitor<T>.OnChange.
namespace Orders;
public sealed record OrderPlaced(Guid OrderId, decimal Total);
// 1. C# event: the language's built-in observer list
public sealed class OrderBook
{
public event EventHandler<OrderPlaced>? Placed;
public void Place(Guid id, decimal total)
{
// ... persist the order ...
Placed?.Invoke(this, new OrderPlaced(id, total)); // reads the delegate once: safe with no subscribers
}
}
public sealed class LoyaltyPoints : IDisposable
{
private readonly OrderBook _book;
public LoyaltyPoints(OrderBook book)
{
_book = book;
_book.Placed += OnPlaced; // the book now holds a reference to this object
}
private void OnPlaced(object? sender, OrderPlaced e) =>
Console.WriteLine($"Award {(int)e.Total} points for {e.OrderId}");
public void Dispose() => _book.Placed -= OnPlaced; // release it, or a long-lived book keeps us alive
}
namespace Sensors;
// 2. IObservable<T>: subscription is an IDisposable. Not thread-safe; use Rx.NET's Subject<T> in real code.
public sealed class TemperatureSensor : IObservable<decimal>
{
private readonly List<IObserver<decimal>> _observers = [];
public IDisposable Subscribe(IObserver<decimal> observer)
{
_observers.Add(observer);
return new Subscription(_observers, observer);
}
public void Publish(decimal reading)
{
foreach (var o in _observers.ToArray()) o.OnNext(reading); // copy: observers may unsubscribe mid-loop
}
public void Complete()
{
foreach (var o in _observers.ToArray()) o.OnCompleted();
_observers.Clear();
}
private sealed class Subscription(List<IObserver<decimal>> observers, IObserver<decimal> observer) : IDisposable
{
public void Dispose() => observers.Remove(observer);
}
}
namespace Pricing;
using Microsoft.Extensions.Options;
public sealed class FeatureFlags { public bool NewCheckout { get; set; } }
// 3. IOptionsMonitor<T>.OnChange: register as a singleton so the subscription lives as long as the monitor
public sealed class FeatureFlagWatcher : IDisposable
{
private readonly IDisposable? _subscription;
public FeatureFlagWatcher(IOptionsMonitor<FeatureFlags> monitor, ILogger<FeatureFlagWatcher> logger)
{
_subscription = monitor.OnChange((flags, _) =>
logger.LogInformation("Feature flags reloaded: NewCheckout={NewCheckout}", flags.NewCheckout));
}
public void Dispose() => _subscription?.Dispose();
}
// Program.cs
// builder.Services.Configure<FeatureFlags>(builder.Configuration.GetSection("FeatureFlags"));
// builder.Services.AddSingleton<FeatureFlagWatcher>();
Dispose, or keep subscriptions in objects with the same lifetime as the publisher.IDisposable returned by Subscribe or IOptionsMonitor<T>.OnChange. Why it is wrong: The subscription is never removed, which leaks and keeps calling dead objects. Instead: Store it in a field and dispose it with the owner.if (Placed != null) Placed(this, e). Why it is wrong: The field is read twice, so a concurrent unsubscribe can cause a NullReferenceException. Instead: Placed?.Invoke(this, e).Channel<T>.GetInvocationList() with a try/catch per handler when isolation matters.IObservable<T> with a plain List<T> in multi-threaded code. Why it is wrong: Concurrent subscribe and publish corrupt the list or break the OnNext/OnCompleted grammar. Instead: Use Rx.NET's Subject<T> or a channel.Observer is cheap to add and easy to get wrong over time, because every subscription is an invisible reference and an invisible call on the publisher's thread. I keep events for genuinely in-process, best-effort notifications (UI updates, cache invalidation, config reload), and move anything that must not be lost to a durable message.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
C# event |
In-process, synchronous, few handlers | Leaks if not unsubscribed; handler exceptions hit the publisher | Work must survive a crash or run asynchronously |
IObservable<T> + Rx.NET |
Streams needing throttling, buffering, composition | Learning curve, extra package | One-off notifications |
IOptionsMonitor<T>.OnChange |
Reacting to config reload | Callback may fire more than once per change | Request-scoped classes (subscribe in singletons) |
Channel<T> |
Decouple producer and slow consumers in-process | Background consumer to manage | Need durability across restarts |
| Broker pub/sub | Cross-service, durable, independently scaled | Infrastructure, eventual consistency | Simple in-process notifications |
An event is a delegate member with access restricted to subscribe and unsubscribe. Outside the class you can only use += and -=; only the owner can raise it or clear it, whereas a public delegate field can be invoked or overwritten by anyone. For a field-like event the compiler generates a private delegate field and thread-safe add and remove accessors. I raise it with Changed?.Invoke(this, e), which reads the field once. I avoid static events because they keep every subscriber alive until it unsubscribes.
It's an Observer lifetime mismatch. The singleton PriceFeed holds every subscriber in its event's invocation list (a strong reference through each delegate's Target), so each request's PriceDisplayService stays reachable long after the request ends. The ignored IDisposable from IOptionsMonitor.OnChange does the same thing.
To prove it: dotnet-counters shows GC heap and gen 2 size climbing without returning to baseline; two dotnet-gcdump snapshots show the PriceDisplayService count growing, with a path to root through PriceFeed β EventHandler β the service.
The fix: unsubscribe in Dispose (the container disposes scoped services at the end of the request), dispose the OnChange token, or better, move the subscription into a singleton that caches the latest price. The trade-off is that per-request subscriptions are almost never what you want; align observer and subject lifetimes.
The convention is EventHandler<TEventArgs> with object? sender and an immutable args object, EventArgs.Empty when there is no data, and a protected virtual OnXxx method that raises it. The big production risk is leaks: the publisher's delegate holds a strong reference to every subscriber, so a singleton or static publisher keeps short-lived subscribers alive forever. I find them with a heap dump and gcroot, which shows the path through the event's delegate, and fix them by unsubscribing in Dispose or using a weak event. Async handlers are async void, so I keep them thin and catch everything inside.
Last updated 18 Nov 2026.