并行处理过程中保持DataTable行的顺序
作者:互联网
以下是当前代码:
Parallel.ForEach(dataTable.AsEnumerable(),row => {
// Code to process the data row to Dictionary<object,object>
// Unique Column name is the Dictionary Key
// ConcurrentDictionary is used for thread safety
});
在这里,我使用Parallel.ForEach将DataTable的行处理为类型Dictionary< object,object>的对象.最终结果是使用中间线程安全结构ConcurrentQueue< Dictionary< object,object>实现的List< Dictionary< object,object>类型,DataTable的源按给定顺序对数据进行排序,但这始终是在并行处理过程中丢失.由于顺序很重要,因此我想出了以下解决方法:
Parallel.For(0,RowCount,index => {
int rowIndex = index;
// Access the rows using the Index
// Final structure will be of type ConcurrentDictionary<Custom>,
// with the RowIndex assigned based on original index
});
Class Custom
{
public int RowIndex { get; set; }
public Dictionary<object,object> DataDictionary {get; set;}
}
类型为ConcurrentQueue< Dictionary< Custom>>的最终结果为使用以下代码处理customObj:
customObj.OrderBy(x=>x.RowIndex).Select(y=>y.DataDictionary).ToList()
以下是我的问题:
>是否有更好的方法来实现相同的并行处理,我可以在其中保持原始订单,这是最重要的业务要求
>在最终解决方案中,我是否需要局部变量rowIndex,我的理解是索引是Parallel循环的一部分,不会导致关闭问题
有指针吗?
解决方法:
那这个呢
var items = new ConcurrentDictionary<DataRow, Dictionary<object,object>>;
Parallel.ForEach(dataTable.AsEnumerable(),row => {
var result = ...;
items.Add(row, result);
});
var finalResult = dataTable.Rows.Cast<DataRow>().Select(r => items[r]).ToList());
标签:parallel-foreach,task-parallel-library,parallel-processing,c 来源: https://codeday.me/bug/20191120/2041096.html