c# - Thread Safety of StringBuilder in Parallel.For -


i have created struct, astruct, , override tostring() method. have written parallel return astruct , put them in list can use streamwriter output them, like

streamwriter sw = new streamwriter(@"abc.txt"); stringbuilder sb = new stringbuilder(); list<astruct> alist = new list<astruct>();  parallel.for(0,10,i =>                          // generate 10 astruct(s) {    alist.add(dosomethingthatreturnsastruct); });  for(int =0; i< alist.count();i++)             //put in stringbuilder {    sb.appendline(alist[i].tostring()); } sw.write(sb.tostring()); sw.close(); 

the problem output file print 7/8 lines of alist, while alist got 10 elements. wonder relate thread-safety of stringbuilder. explain why not lines output?

in code above instance of stringbuilder never accessed/modified other main thread (or whatever thread creating sw) thread-safety of stringbuilder not relevant however have bigger bug 1 should remember when dealing more 1 thread.

never ever modify shared resource multiple threads unless resource thread-safe

you updating alist different threads either use lock synchronize access or thread-safe collection e.g. concurrentqueue (order guaranteed) or concurrentbag (order not guaranteed)

you adding 9 entries alist instead of 10.

finally here's modified code yields expected result.

var sw = new streamwriter(@"abc.txt"); try {             var alist = new list<astruct>();      var locker = new object();     parallel.for(0, 10, =>                          // generate 10 astruct(s)     {         lock (locker) { alist.add(new astruct()); }     });      var sb = new stringbuilder();     (int = 0; < alist.count; i++)             //put in stringbuilder     {         sb.appendline(alist[i].tostring());     }     sw.write(sb.tostring()); } {     sw.close(); } 

Comments