I have created a struct, say AStruct
, and override its ToString()
method. Then I have written a parallel for to return some AStruct
and put them in a list so I can use a StreamWriter
to 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 i =0; i< AList.Count();i++) //put in a StringBuilder
{
sb.AppendLine(AList[i].ToString());
}
sw.Write(sb.ToString());
sw.Close();
The problem is the output file only print 7/8 lines of AList, while AList actually got all the 10 elements. I wonder does this relate to thread-safety of StringBuilder. Could someone explain why not all lines are output?