Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
C#

C#: Fix the Null Reference Exception That Only Happens After Awaiting an Async Method

- 31.08.26 - ErcanOPAK

🔧 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.

— C# Best Practice

Related posts:

C#: Use Caller Info Attributes for Better Logging Without Reflection

C#: Use Caller Info Attributes for Better Logging Without Reflection

LINQ Causing Hidden Allocations

LINQ Causing Hidden Allocations

C#: Why a Using Declaration Doesn't Dispose Until the End of the Enclosing Block, Not the Next Line

C#: Why a Using Declaration Doesn't Dispose Until the End of the Enclosing Block, Not the Next Line

Views: 14

Post navigation

ASP.NET Core: Fix Model Binding That Silently Returns Null for a Perfectly Valid Request Body
WordPress: Fix a Contact Form That Stops Sending Emails After a Host Migration

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

November 2026
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
30  
« Oct    

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,068)
  • Get the User Name and Domain Name from an Email Address in SQL (990)
  • How to add default value for Entity Framework migrations for DateTime and Bool (986)
  • Get the First and Last Word from a String or Sentence in SQL (865)
  • How to select distinct rows in a datatable in C# (859)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (661)
  • Add Constraint to SQL Table to ensure email contains @ (619)
  • Average of all values in a column that are not zero in SQL (577)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (553)
  • Find numbers with more than two decimal places in SQL (481)

Recent Posts

  • Network Speed Monitor Windows Application v2.5.1
  • Ağ Hızı İzleyici Windows Uygulaması v2.5.1
  • How to make theater mode the default for Youtube
  • The AI Prompt That Audits a Function for Thread-Safety Gaps
  • Ajax: Fix a Fetch Request Caching a Response Despite No-Store
  • WordPress: Fix a Navigation Block Losing Submenu Items After Sync
  • Visual Studio: Fix CodeLens Reference Counts Stuck at Stale Numbers
  • C#: Fix a UTF-8 String Literal Behaving Differently in a Switch
  • Photoshop: Fix a Liquify Mesh Snapping Back on a Smart Object
  • The AI Prompt That Turns a Crash Dump Into a Short Repro Script

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,068)
  • Get the User Name and Domain Name from an Email Address in SQL (990)
  • How to add default value for Entity Framework migrations for DateTime and Bool (986)
  • Get the First and Last Word from a String or Sentence in SQL (865)
  • How to select distinct rows in a datatable in C# (859)

Recent Posts

  • Network Speed Monitor Windows Application v2.5.1
  • Ağ Hızı İzleyici Windows Uygulaması v2.5.1
  • How to make theater mode the default for Youtube
  • The AI Prompt That Audits a Function for Thread-Safety Gaps
  • Ajax: Fix a Fetch Request Caching a Response Despite No-Store

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com