首页 > 代码库 > StringBuilder是不是线程安全的?

StringBuilder是不是线程安全的?

测试条件:

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

测试代码:

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

测试结果:

 

结论:

     StringBuilder是线程安全的

StringBuilder是不是线程安全的?