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 a StringBuilder Shared as a Static Field Producing Garbled, Interleaved Output Under Concurrent Use Because StringBuilder Was Never Designed to Be Thread-Safe

- 10.11.26 - ErcanOPAK

🔧 Fix a StringBuilder Shared as a Static Field Producing Garbled, Interleaved Output Under Concurrent Use Because StringBuilder Was Never Designed to Be Thread-Safe

StringBuilder’s documentation states plainly that an instance is not safe for concurrent use by multiple threads, but nothing about declaring one as a static field enforces that restriction at compile time or even at first run — a single shared StringBuilder used to build up a request’s log output, or to accumulate results across a parallel operation, works perfectly in testing with sequential calls and only exposes the problem once two threads actually call Append on it at close to the same moment, at which point its internal character buffer and length tracking can end up corrupted, producing garbled, interleaved, or truncated text instead of a clean exception that would point straight at the cause.

🔎 The Problem

private static readonly StringBuilder _requestLog = new();

public void LogRequest(string message)
{
    _requestLog.Append(DateTime.UtcNow).Append(": ").Append(message).Append('\n');
    // called from many concurrent request-handling threads
}

// Under load, _requestLog's contents end up with interleaved, truncated,
// or duplicated fragments of different log lines mixed together -
// no exception thrown, just corrupted text

✅ Fix: Don’t Share One StringBuilder Across Threads at All

  • Give each thread or each request its own local StringBuilder instance instead of sharing one static instance, which is almost always the right fix since a shared mutable text buffer across concurrent operations rarely needs to be the same object in the first place.
  • If output genuinely must be aggregated from multiple threads into one place, use a thread-safe primitive built for that — a ConcurrentQueue<string> of completed lines, or a proper logging framework’s own buffering — rather than a raw shared StringBuilder.
  • If a single shared instance absolutely cannot be avoided, wrap every access to it in an explicit lock, understanding that this serializes every append and may itself become a bottleneck under enough concurrent load.

🚨 Why This Is Dangerous

  • Because the corruption shows up as mangled text rather than a thrown exception, this bug can sit in production logging code for a long time producing subtly wrong log output that nobody traces back to a concurrency bug, especially if the garbled lines are rare enough to look like one-off formatting glitches.

StringBuilder optimizes for one thread building text efficiently — handing it to several threads at once doesn’t make it faster, it makes its internal bookkeeping wrong.

— C# Best Practice

Related posts:

C#: Fix a Local Function Failing to Compile Over a Span Parameter With a Cannot Use a Result of ref ...

C#: Fix a Local Function Failing to Compile Over a Span Parameter With a Cannot Use a Result of ref ...

C#: Fix a Source-Generated Regex Partial Method Silently Falling Back to a Different Culture Than th...

C#: Fix a Source-Generated Regex Partial Method Silently Falling Back to a Different Culture Than th...

C# LINQ Queries Allocate Too Much

C# LINQ Queries Allocate Too Much

Views: 5

Post navigation

ASP.NET Core: Fix a File Upload Endpoint Rejecting Anything Over 30MB Because Kestrel’s Own Request Body Size Limit Is Configured Completely Separately From IIS’s
Docker: Fix ‘No Space Left on Device’ Coming Back Right After a Prune Because BuildKit’s –mount=type=cache Build Cache Isn’t Touched by a Plain docker system prune

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,055)
  • Get the User Name and Domain Name from an Email Address in SQL (980)
  • How to add default value for Entity Framework migrations for DateTime and Bool (977)
  • Get the First and Last Word from a String or Sentence in SQL (857)
  • How to select distinct rows in a datatable in C# (854)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (653)
  • Add Constraint to SQL Table to ensure email contains @ (608)
  • Average of all values in a column that are not zero in SQL (570)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (546)
  • Find numbers with more than two decimal places in SQL (475)

Recent Posts

  • C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
  • Docker: Fix a Stale COPY Layer After Editing .dockerignore
  • Photoshop: Fix a Pattern Overlay Scaling Wrong on a High-DPI File
  • SQL Server: Fix a Computed Column Index Skipped by Implicit Cast
  • HTML5: Fix a required Input Inside a Hidden Tab Blocking Submit
  • SQL Server: Fix ROW_NUMBER Ties Reordering Between Identical Runs
  • C#: Fix an Enum HasFlag Returning True for the Zero Value
  • WordPress: Fix Featured Images Vanishing After a CDN Migration
  • Photoshop: Fix Content-Aware Fill Smearing a Repeating Pattern
  • Asp.Net Core: Fix Antiforgery Tokens Rejected Behind a Reverse Proxy

Most Viewed Posts

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

Recent Posts

  • C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
  • Docker: Fix a Stale COPY Layer After Editing .dockerignore
  • Photoshop: Fix a Pattern Overlay Scaling Wrong on a High-DPI File
  • SQL Server: Fix a Computed Column Index Skipped by Implicit Cast
  • HTML5: Fix a required Input Inside a Hidden Tab Blocking Submit

Social

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