Parallel foreach on DataTable in C#

By | March 21, 2018

Once, we had one situation where foreach loop is used to loop though data rows in datatable and we were marking DB call though that loop. [Calling DB functions inside loop is not good practice, but that code was very old and we just wanted to improve some performance.] but we wanted Parallel foreach on DataTable.

the condition was like,

   foreach(DataRow drow in dt.Rows)
   {
       // calculations and db call
   }

so we changed this as below,

Parallel.ForEach(
dt.AsEnumerable(), 
row =>
{
   // calculations & DB call
});

Parallel.ForEach() expects the first argument to be an IEnumerable<> type.

DataTable.Rows is not IEnumerable type, but we can turn it into one with the AsEnumerable() extension method.

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *