【发布时间】:2015-09-27 21:01:37
【问题描述】:
想象一下,我为一个有很多属性的学生准备了以下课程,让我们将其简化为:
public class Student{
public Int64 id { get; set; }
public String name { get; set; }
public Int64 Age { get; set; }
}
然后在主线程上我得到了以下列表:
List<Student> allStudents = new List<Student>();
假设我在一个 Excel 文件中有 500 名学生,我想收集他们并将他们插入到列表中。我可以这样做:
for(int i = startRow; i < endRow; i++){
Student s = new Student();
//Perform a lot of actions to gather all the information standing on the row//
allStudents.Add(s);
}
现在因为在 Excel 中收集信息非常慢,因为必须执行许多操作。所以我想用Parallel.For,我可以想象做以下事情:
Parallel.For(startRow, endRow, i => {
Student s = new Student();
//Perform a lot of actions to gather all the information standing on the row//
//Here comes my problem. I want to add it to the collection on the main-thread.
allStudents.Add(s);
});
在上述问题中实现 Parallel.For 的正确方法是什么?我应该在添加之前锁定列表吗?如何锁定?
@编辑 15:52 09-07-2015
下面的回答结果如下(524条记录):
- 2:09 分钟 - 正常循环
- 0:19 分钟 - AsParallel 循环
【问题讨论】:
标签: c# multithreading parallel-processing locking