🔧 The Object Was Never Null – Until You Awaited Something
A method reads a field, awaits an async call, then reads that same field again a few lines later — and the second read throws a NullReferenceException, even though nothing in the visible code path ever set it to null.
🐞 The Problem
public class OrderProcessor
{
private Order _currentOrder;
public async Task ProcessAsync()
{
_currentOrder = await LoadOrderAsync();
await SaveAuditLogAsync(); // <- await point
// NullReferenceException here, intermittently:
Console.WriteLine(_currentOrder.Id);
}
}
🔍 Why This Happens
Every "await" is a point where the current thread can go do other work and come back later - and if _currentOrder is an INSTANCE field (not a local variable) on an object that's reused across concurrent requests (a scoped or singleton service, a shared handler instance), another concurrent call can run its OWN ProcessAsync() in between your await and your next line, and overwrite or reset that same shared field before you resume.
✅ The Fix: Never Share Mutable State on an Object Used Concurrently
- Use a LOCAL variable instead of an instance field for anything read after an await, whenever the containing object could be shared across concurrent calls:
var order = await LoadOrderAsync(); - If the service genuinely needs per-request state, register it as Scoped (not Singleton) in DI so each request gets its own instance – eliminating the sharing entirely instead of working around it.
- For state that must be shared, protect it properly (a lock, or better, redesign to avoid mutable shared state across awaits) rather than assuming ‘it usually works.’
⚠️ Why This Is So Hard to Reproduce
- It only manifests under real concurrency (two requests actually overlapping around the same await point), which is exactly why it can pass every manual test and every low-traffic staging environment, then appear under production load.
- The exception’s stack trace points at the SYMPTOM (the null read) not the CAUSE (the concurrent overwrite) – if this pattern is even a possibility, audit every instance field touched around an await, not just the one that crashed.
Async doesn’t just pause your code — it opens a window for someone else’s code to run in the meantime, and a shared field is exactly what falls through that window.
