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