The Parallel. ForEach method splits the work to be done into multiple tasks, one for each item in the collection. Parallel. ForEach is like the foreach loop in C#, except the foreach loop runs on a single thread and processing take place sequentially, while the Parallel.
You don't have to do anything special, Parallel. Foreach() will wait until all its branched tasks are complete. From the calling thread you can treat it as a single synchronous statement and for instance wrap it inside a try/catch.
DataTable.Rows
returns a DataRowCollection
which only implements IEnumerable
, not IEnumerable<DataRow>
. Use the AsEnumerable()
extension method on DataTable
(from DataTableExtensions
) instead:
Parallel.ForEach(dt.AsEnumerable(), drow =>
{
...
Do Stuff
...
});
This is better than the accepted answer because this does not need to reference System.Data.DataSetExtensions:
Parallel.ForEach(dt.Rows.Cast<DataRow>(), dr =>
To use ForEach with a non-generic collection, you can use the Cast extension method to convert the collection to a generic collection, as shown in this example.
Parallel.ForEach() expects the first argument to be an IEnumerable<> type. DataTable.Rows is not, but you can turn it into one with the AsEnumerable() extension method. Try:
... Parallel.ForEach(dt.AsEnumerable(), drow => ...
This way we can use Parallel.ForEach for Data table.
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);
Parallel.ForEach(dtTest.AsEnumerable(), drow =>
{
MessageBox.Show("ID " + drow.Field<int>("ID") + " " + drow.Field<string>("Name") + " " + drow.Field<int>("Salary"));
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With