In C#, are += and -= on a field-like event thread-safe, and what does the compiler generate for its add and remove accessors?
answer
- accessors you never wrote
- Combine, then compare-and-swap
- retry when the field moved
- custom accessors lose it
basics
~20 sYes. The compiler-generated add and remove accessors build a new delegate with Delegate.Combine or Delegate.Remove and publish it with Interlocked.CompareExchange in a retry loop, so concurrent subscriptions are not lost. Hand-written accessors get none of that.
solid answer
~30 sFor a field-like event the compiler writes `add_PriceChanged` and `remove_PriceChanged` itself. Each reads the backing field, builds a new delegate with `Delegate.Combine` or `Delegate.Remove`, and stores it with `Interlocked.CompareExchange`, retrying if another thread changed the field in the meantime. So two dashboards subscribing at once from different threads cannot overwrite each other. That covers only the accessors: raising still needs a single read, `?.Invoke`; handlers still run on the raising thread; and once you write custom `add` and `remove` bodies, the safety is yours to provide, typically with a `lock`.
code
csharp · 30 linesvar fieldLike = new FieldLikeTicker();
var naive = new NaiveTicker();
Parallel.For(0, 4, _ =>
{
for (int i = 0; i < 2_000; i++)
{
fieldLike.PriceChanged += (s, e) => { };
naive.PriceChanged += (s, e) => { };
}
});
Console.WriteLine($"field-like event: {fieldLike.Count} of 8000");
Console.WriteLine($"naive accessors: {naive.Count} of 8000");
class FieldLikeTicker
{
public event EventHandler? PriceChanged;
public int Count => PriceChanged?.GetInvocationList().Length ?? 0;
}
class NaiveTicker
{
private EventHandler? _priceChanged;
public event EventHandler? PriceChanged
{
add => _priceChanged += value; // read, combine, write: no synchronization
remove => _priceChanged -= value;
}
public int Count => _priceChanged?.GetInvocationList().Length ?? 0;
}go deeper
Know that subscribing to a field-like event from several threads does not lose subscriptions, and that this applies to += and -=, not to the handlers themselves.
Explain the generated accessors: Delegate.Combine or Remove builds a new delegate, and Interlocked.CompareExchange stores it, retrying when the field changed.
Catch the review trap: hand-written add and remove bodies drop the generated synchronization, so they need a lock or a compare-and-swap loop of their own.
Separate the three guarantees a publisher can offer: list updates, the raise snapshot, and handler threading, and state which ones each component promises.
## The accessors you did not write Declaring `public event EventHandler? PriceChanged;` creates a **field-like event**. The compiler emits three things: - a private backing field of type `EventHandler?`; - an `add_PriceChanged` method, which `ticker.PriceChanged += handler` calls; - a `remove_PriceChanged` method, which `-=` calls. A **delegate** is immutable, so subscribing cannot change the delegate already stored. Each accessor computes a replacement and has to store it without losing a change made by another thread at the same moment. ## What the generated add does Current C# compilers generate a lock-free **compare-and-swap loop**. In C# terms the add accessor is equivalent to: ```csharp EventHandler? current = _priceChanged, observed; do { observed = current; var combined = (EventHandler?)Delegate.Combine(observed, value); current = Interlocked.CompareExchange(ref _priceChanged, combined, observed); } while (current != observed); ``` 1. Read the field. 2. Build a new delegate with `Delegate.Combine` (or `Delegate.Remove` in the remove accessor). 3. `Interlocked.CompareExchange` stores the new delegate only if the field still holds the value read in step 1, and returns what it found. 4. If another thread got there first, the loop retries with the fresh value. Inspecting the IL of `add_PriceChanged` shows two calls, `Delegate.Combine` and `Interlocked.CompareExchange`, followed by a backward branch that compares the two values and loops. The Roslyn compiler's breaking-change notes for Visual Studio 2015 record that `Interlocked.CompareExchange` is required when declaring field-like events, and that an error is reported when targeting a platform that lacks it. ## What it guarantees and what it does not | Concern | Field-like event | Custom accessors written naively | |---|---|---| | Concurrent `+=` from many threads | no subscription lost | subscriptions can be lost | | Concurrent `-=` | no removal lost | removals can be lost or undone | | Raising while others subscribe | safe with `?.Invoke` | safe with a single read of your own field | | Handler thread | the thread that raises | the thread that raises | | Handler's own state | subscriber's job | subscriber's job | The guarantee is **atomic, linearizable updates of the invocation list**. It is not an ordering guarantee between a subscription and a raise in progress: a raise works on the snapshot it read. Nor does it make handlers thread-safe: a dashboard handler that updates a shared dictionary still needs its own synchronization. ## When you write the accessors yourself With custom accessors, `add` and `remove` are ordinary methods and the compiler adds nothing. The obvious body, `add => _priceChanged += value;`, is a read, a combine and a write with no synchronization. Two threads can read the same old value, each combine their own handler, and the second write discards the first. In the demo below, five test runs lost between roughly 1,100 and 2,300 of 8,000 concurrent subscriptions through such accessors, while the field-like event kept all 8,000 every time. Two correct options for custom accessors: - **Take a lock** around the read and write, for example `add { lock (_gate) { _priceChanged += value; } }`. Simple, and the lock also lets you do bookkeeping atomically. Keep the raise outside the lock, invoking a snapshot of the field, so handlers never run while the lock is held. - **Reproduce the loop** with `Interlocked.CompareExchange`, which is what the compiler does. It is lock-free but harder to review. The choice between the `lock` statement, the `System.Threading.Lock` type and `Interlocked` is covered in the lesson on locks and atomics. ## How interviewers probe it Expect a sequence: "Is `+=` on an event thread-safe?" (yes, for field-like events), "How?" (Combine plus a compare-and-swap loop), "What about raising?" (read once with `?.Invoke`), "What if I write my own accessors?" (then synchronization is your job). A strong answer keeps three layers apart: updating the list, reading it to raise, and the handlers' own state.
- If += on a field-like event is thread-safe, why do you still raise it with ?.Invoke?The accessors make updating the backing field atomic, but raising reads that field from your own code. `if (PriceChanged != null) PriceChanged(this, e)` reads it twice, and the last `-=` can set it to `null` between the reads. `?.Invoke` reads it once and invokes that immutable snapshot.
- How do you make custom add and remove accessors on a C# event safe for concurrent subscribers?Synchronize the read-combine-write yourself: wrap `_priceChanged += value` and `-= value` in a `lock` on a private object, or replicate the compiler's `Interlocked.CompareExchange` loop. Raise outside the lock by invoking a snapshot of the field, so handlers never run while the lock is held.
- Events are not thread-safe at all, so every += needs an external lock.
- The compiler-generated add accessor locks on this.
- Custom add and remove accessors inherit the compiler's synchronization.
- Thread-safe subscription means handlers run on the subscriber's thread.
- Atomic += also makes the null-check-then-call raise safe.