title: Correct way of using Parallel.ForEach loop in C# for data consistency
body: <p>I am trying to create an xml by looping through  <code>List&lt;TestRequest&gt;.</code>
  for better performance , i am trying <code>Parallel.ForEach</code> for looping as there are thousands of records in the list however i am not getting consistent data
  in <code>xml</code>, sometime there is a truncation in <code>xml</code> string while appending to string builder and sometimes there is data mismatch.
  below is the code</p>
  
  <pre><code>   public class Program
      {
  
  
          static void Main(string[] args)
          {
              List&lt;TestRequest&gt; ids = new List&lt;TestRequest&gt;();
              Random rnd = new Random();
              int id = rnd.Next(1, 12345);
              for (int i = 1; i &lt; 1000; i++)
              {
                  var data = new TestRequest();
                  data.dataId = id;
                  ids.Add(data);
              }
  
              var xmlData = GetIdsinXML(ids);
  
          }
  
          private static string GetIdsinXML(List&lt;TestRequest&gt; Ids)
          {
              var sb = new StringBuilder();
              sb.Append("&lt;ROOT&gt;");
  
              Parallel.ForEach(Ids, id =&gt;
              {
  
                  sb.Append("&lt;Row");
                  sb.Append(" ID='" + id.dataId + "'");
                  sb.Append("&gt;&lt;/Row&gt;");
  
  
              }
              );
  
  
              sb.Append("&lt;/ROOT&gt;");
              return sb.ToString();
          }
  
  
      }
  
      public class TestRequest
      {
          public int dataId { get; set; }
  
      }
  </code></pre>
  
  <p>is this is the correct way of using Parallel.ForEach ?</p>
  
  <p>Please help.
  Thanks!</p>