In C#, why is if (PriceChanged != null) PriceChanged(this, e) unsafe when dashboards unsubscribe from other threads, and what fixes it?
answer
- two reads of one field
- last subscriber leaves in between
- NullReferenceException on the second read
- ?. evaluates its operand once
- delegates are immutable
basics
~20 sThe check and the call read the event's backing field separately; if the last handler unsubscribes in between, the call hits null and throws NullReferenceException. PriceChanged?.Invoke(this, e) reads the field once and invokes that immutable delegate.
solid answer
~40 sInside the publisher, `PriceChanged` is the backing field, and `if (PriceChanged != null) PriceChanged(this, e);` reads it twice. Another thread running `-=` on the last subscriber can set it to `null` between the two reads, so the call throws `NullReferenceException`. The fix is to read it once: `PriceChanged?.Invoke(this, e);`, or the older `var handler = PriceChanged; if (handler != null) handler(this, e);`. Delegates are immutable, so `+=` and `-=` store a new delegate rather than changing the one already read. The price of the snapshot is that a handler removed during the raise may still run once, so subscribers must tolerate a late call.
code
csharp · 21 linesvar ticker = new StockTicker();
EventHandler<decimal>? second = null;
EventHandler<decimal> first = (s, p) =>
{
Console.WriteLine($"first sees {p}, unsubscribes second");
ticker.PriceChanged -= second;
};
second = (s, p) => Console.WriteLine($"second sees {p}");
ticker.PriceChanged += first;
ticker.PriceChanged += second;
ticker.Update(100m); // second still runs: the raise uses the delegate it read
ticker.Update(101m); // now only first runs
class StockTicker
{
public event EventHandler<decimal>? PriceChanged;
// ?.Invoke reads the field once; the delegate it read is immutable
public void Update(decimal price) => PriceChanged?.Invoke(this, price);
}go deeper
Remember to raise events with PriceChanged?.Invoke(this, e), not with a separate null check followed by a call.
Explain the two reads of the backing field, the window between them, and why a delegate snapshot cannot change after it is read.
Name the snapshot's cost in production: a handler may run once after unsubscribing, handlers run on the raising thread, and one exception skips the rest.
Decide what the publisher promises subscribers about late calls, threads and exceptions, and document it on the event rather than leaving each subscriber to guess.
## What the two-read version actually does Inside the class that declares a **field-like event** (an event declared without custom `add` and `remove` accessors), the event's name refers to a compiler-generated private field holding a **delegate**: an object listing the handler methods to call. Subscribing and unsubscribing replace that field's value. Consider a stock-ticker class that raises `PriceChanged` for dashboards that subscribe and unsubscribe from several threads: ```csharp // two reads of the backing field if (PriceChanged != null) PriceChanged(this, e); ``` The condition reads the field, and the call reads it again. Between the two reads another thread can run `ticker.PriceChanged -= handler` for the last remaining subscriber. Removing the last handler leaves the field `null`, so the second read gets `null` and the call throws **`NullReferenceException`** inside the publisher, even though the code "checked for null". It is a classic **check-then-act race**: rare, timing-dependent, and nearly impossible to reproduce on a developer machine. ## The fix: read the field once Both standard fixes read the field a single time and use the value they read: ```csharp PriceChanged?.Invoke(this, e); // the modern form var handler = PriceChanged; // the older explicit form if (handler != null) handler(this, e); ``` Microsoft's documentation of the null-conditional operator states that `?.` evaluates its left-hand operand no more than once, and calls this the thread-safe way to invoke a delegate when raising an event. The IDE style rule **IDE1005** ("Use conditional delegate call") suggests the `?.Invoke` form when it finds the null-check version. ## Why a snapshot is enough: delegates are immutable A local copy only helps because a delegate object never changes after it is created: - `+=` calls `Delegate.Combine`, which builds a **new** delegate containing the old handlers plus the new one. - `-=` calls `Delegate.Remove`, which builds a new delegate without the handler, or returns `null` when nothing is left. - The event then stores the new delegate in its field. Whatever delegate another thread already read still holds exactly the handlers it held at that moment. So the value captured by `?.Invoke` or the local `handler` is a stable snapshot. No other thread can empty it or add to it while the raise is running. ## The trade-off the snapshot creates 1. **A handler can run after it unsubscribed.** If a dashboard unsubscribes after the publisher took the snapshot, the dashboard's handler still runs for that raise. The example below shows it deterministically: the first handler removes the second during a raise, and the second still runs that time. Subscribers that dispose resources on unsubscribe must tolerate one late call, for example by checking their own disposed flag. 2. **A new subscriber may miss the raise in progress.** A handler added after the snapshot first runs on the next raise. 3. **Handlers still run on the raising thread.** `?.Invoke` fixes the null race, not threading: every handler runs synchronously on whichever thread raised the event, one after another. 4. **A throwing subscriber stops the rest.** An exception from one handler propagates out of `Invoke` to the publisher, and handlers later in the list do not run for that raise. ## What it does not fix | Concern | Fixed by `?.Invoke`? | |---|---| | `NullReferenceException` when the last handler leaves mid-raise | yes | | A handler running once after it unsubscribed | no, inherent to the snapshot | | Lost subscriptions when threads `+=` concurrently | not the raise's job; field-like `add` and `remove` already handle it | | Handlers touching UI or shared state from the raising thread | no, the subscriber must marshal or synchronize | | One handler's exception skipping the rest | no | Reviewers raise this most often in classes that publish from timer callbacks, background workers or socket readers while the UI subscribes and unsubscribes. The fix costs nothing, so the null-check-then-call form should not survive review even in single-threaded code.
- After a dashboard unsubscribes from PriceChanged on another thread, can its handler still be called?Yes, once. If the publisher read the delegate with `?.Invoke` just before the `-=`, that snapshot still contains the handler and runs it. Removing a handler only affects raises that read the field afterwards. A subscriber that tears down state on unsubscribe should ignore a call that arrives after it disposed.
- What happens to the remaining dashboards when one PriceChanged handler throws during PriceChanged?.Invoke(this, e)?The exception propagates out of `Invoke` into the publisher's raising method, and the handlers after the thrower in the invocation list do not run for that raise. `?.Invoke` only protects against the null race; a publisher that must isolate subscribers has to call each handler separately inside its own `try` block.
A teacher photographs the sign-up sheet and reads names from the photo. A student who crosses their name off the sheet after the photo is still called this time, and the photo can never turn blank midway through the reading.
- Checking PriceChanged != null right before calling it makes the raise thread-safe.
- -= modifies the delegate the publisher already read, so a snapshot can go null.
- ?.Invoke runs the handlers on a thread-pool thread instead of the caller.
- After -= returns, the removed handler can never run again.
- ?.Invoke also stops one throwing handler from skipping the others.