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