C# Datatable .AsParallel() AsOrdered() not giving data in order

  • Thread starter Thread starter Sudip_inn
  • Start date Start date
S

Sudip_inn

Guest
I have created data table and store some test data there just to see how AsParallel() with AsOrdered() works but when i test the code then i saw i am not getting data in any specific order. ever time i am executing code the order is getting different. so what is lack in my code for which i am not getting data in order?

see my sample code

DataTable dtTest = new DataTable();
dtTest.Columns.Add("ID",typeof(int));
dtTest.Columns.Add("Name", typeof(string));
dtTest.Columns.Add("Salary", typeof(int));

DataRow dr = dtTest.NewRow();
dr["ID"] = 1;
dr["Name"] = "Rom";
dr["Salary"] = "2000";
dtTest.Rows.Add(dr);

dr = dtTest.NewRow();
dr["ID"] = 2;
dr["Name"] = "David";
dr["Salary"] = "5000";
dtTest.Rows.Add(dr);

dr = dtTest.NewRow();
dr["ID"] = 3;
dr["Name"] = "Samy";
dr["Salary"] = "1200";
dtTest.Rows.Add(dr);


StringBuilder sb = new StringBuilder();
sb.Append("<table>");
sb.Append("<thead><tr><th>ID</th><th>Name</th><th>Salary</th></tr></thead>");
sb.Append("<tbody>");

var htmltables = dtTest.AsEnumerable().AsParallel().AsOrdered().Select(a =>
{
MessageBox.Show("ID " + a.Field<int>("ID").ToString());

return sb.Append("<tr><td>" + a.Field<int>("ID").ToString()
+ "</td><td>" + a.Field<string>("Name").ToString()
+ "</td><td>" + a.Field<int>("Salary").ToString()
+"</td></tr>");

}).ToList();

sb.Append("</tbody></table>");

if anyone run my test code in .net 4.5.2 then must notice this ID order is getting different when i am showing through message box. i am talking about this line MessageBox.Show("ID " + a.Field<int>("ID").ToString());

so when i am composing table inside parallel loop then records whose ID is 1 that is sometime coming at end or in the second position. so how can i use AsParallel() with AsOrdered() as result ID should be in order ?

i do not want to use Lock{} statement because then freedom of multi thread will be finish.

please guide me how to get data in order with multi threading. thanks



Continue reading...
 
Back
Top