我正在处理+100000行并实现了Parallel。这样可以加快处理速度
逻辑行为将是:100000条记录,其中85000 groupId意味着MyItems应该拥有85000条记录。
情况并非如此......我最终获得的金额不同于85000
该过程如下:
从DB获取所有值
在整数数组中获取所有ID(不是行ID' s,而是groupId)
处理groupId&#39>
var myItems = new List<MyItem>(IDCounter.Length);
Parallel.For(0, IDCounter.Length, (i, loopState) =>
{
if(!SomeParameter)
loopState.Stop();
var records = (from m in AllValues where m.GroupId == IDCounter[i] select m).ToList();
var recordList = new List<MyRecords>();
for(var j = 0; j<records.Count; j++)
{
recordList.Add(new MyRecord{Text = records[j].OtherValue});
}
myItems.Add(new MyItem(Text = records[0].SomeValue, List = recordList));
});
有什么想法吗?
答案 0 :(得分:3)
您同时多次呼叫myItems.Add
。确保它是线程安全的。
答案 1 :(得分:2)
为了确保您不会同时向列表中添加项目,您可以使用concurrent collection。
System.Collections.Concurrent
命名空间提供了几个线程安全的集合类,只要多个线程同时访问集合,就应该使用它们代替System.Collections
和System.Collections.Generic
命名空间中的相应类型。
一个例子是使用ConcurrentBag
,因为您无法保证将添加项目的顺序。
表示线程安全,无序的对象集合。
另一种方法是在添加到列表时使用锁定,以确保在任何给定时间只添加一个项目。