"is .net's stringbuilder thread-safe" Code Answer


absolutely not; here's a simple example lifted from 4.0 via reflector:

public stringbuilder append(char value)
    if (this.m_chunklength < this.m_chunkchars.length)
        this.m_chunkchars[this.m_chunklength++] = value;
        this.append(value, 1);
    return this;

the attribute just handles callers, not thread-safety; this is absolutely not thread-safe.

update: looking at the source he references, this is clearly not the current .net 4.0 code-base (comparing a few methods). perhaps he is talking about a particular .net version, or maybe xna - but it is not the case in general. the 4.0 stringbuilder does not have a m_currentthread field, which gavin's source material uses; there's a hint (an unused constant threadidfield) that it used to exist, but... no longer.

if you want a direct disproof - run this on 4.0; it will most likely give the wrong length (i've seen a few in the 4k region, a few in the 2k region - it should be exactly 5000), but some other append methods (append(char) for example) tend more likely to throw exceptions, depending on timing:

var gate = new manualresetevent(false);
var alldone = new autoresetevent(false);
int counter = 0;
var sb = new stringbuilder();
threadstart work = delegate
    // open gate when all 5 threads are running
    if (interlocked.increment(ref counter) == 5) gate.set();
    else gate.waitone();

    for (int i = 0; i < 1000; i++) sb.append("a");

    if (interlocked.decrement(ref counter) == 0) alldone.set();
for(int i = 0 ; i < 5 ; i++)
    new thread(work).start();
By Adib Faramarzi on April 7 2022

Answers related to “is .net's stringbuilder thread-safe”

Only authorized users can answer the Search term. Please sign in first, or register a free account.