StringBuilder是不是线程安全的?

时间:2023-11-09 18:42:08

测试条件:

开启2个并行执行任务,往同一个StringBuilder对象写入值

测试代码:

static int maxNum = ;
static StringBuilder sbIsThreadSafe = new StringBuilder();
static void Main(string[] args)
{
//迭代次数
int iterationNum = ;
CodeTimer.Initialize();
CodeTimer.Time("StringBuilder是否是线程安全的呢?", iterationNum, new Action(SBIsThreadSafe));
//Console.Write(sbIsThreadSafe.ToString());
Console.Read();
}
private static void SBIsThreadSafe()
{
Parallel.For(, maxNum / , (i) =>
{
sbIsThreadSafe.Append(i.ToString());
});
Parallel.For(maxNum / + , maxNum, (i) =>
{
sbIsThreadSafe.Append(i.ToString());
});
}

测试结果:

StringBuilder是不是线程安全的?

结论:

StringBuilder是线程安全的