Task多线程操作datatable
本文关键字: c#, datatable, Task, 多线程一个c#项目,将datatable1遍历,然后处理到克隆的datatable2上面
if (dt.Rows.Count > 0) {
int taskcount=2;Task[] tasks = new Task[taskcount];
for (int i = 0; i < taskcount; i++)
{
tasks[i] = Task.Factory.StartNew(() =>
{
try
{ DoSomeWork(); }
catch (Exception ex) { MessageBox.Show(ex.Message); }
}
, TaskCreationOptions.LongRunning); ;
}
//// Wait for all tasks to complete.
Task.WaitAll(tasks);
}
然后lock 取值datatable1里面的Rows的每一行,在datatable2里面Add的操作时候一定要 lock
lock (dt2.Rows.SyncRoot)
{
dt2.Rows.Add(r.ItemArray);
}