我有这个
foreach (FileInfo flInfo in dir.GetFiles())
{
String name = flInfo.Name;
Console.WriteLine("{0, -30:g} ", name);
Task<DataTable> mergeTable = processFile(name);
table.Merge(mergeTable.Result);
}
如何使用不同的变量mergeTable循环此任务
更具体地说明我要的是什么 目前,我正在这样做。
Task<DataTable> mergeTable01 = processFile("filename1.txt");
Task<DataTable> mergeTable02 = processFile("filename2.txt");
Task<DataTable> mergeTable03 = processFile("filename3.txt");
Task<DataTable> mergeTable04 = processFile("filename4.txt");
Task.WaitAll(mergeTable01,mergeTable02,mergeTable03,mergeTable04);
table.Merge(mergeTable01.Result);
table.Merge(mergeTable02.Result);
table.Merge(mergeTable03.Result);
table.Merge(mergeTable04.Result);
如何循环执行此重复任务并最终合并数据表?
答案 0 :(得分:1)
如果您要触发所有任务以异步处理,则需要按照Kevin的说法启动并将它们添加到List<Task<T>>
中,然后在该集合上调用Task.WhenAll
。
List<Task<DataTable>> dataTableTasks = new List<Task<DataTable>>();
foreach (FileInfo flInfo in dir.GetFiles())
{
String name = flInfo.Name;
Console.WriteLine("{0, -30:g} ", name);
Task<DataTable> mergeTable = processFile(name);
dataTableTasks.Add(mergeTable);
}
await Task.WhenAll(dataTableTasks);
foreach(Task<DataTable> dataTableTask in dataTableTasks)
{
table.Merge(await dataTableTask);
}