如何填写列表< >在主线程上使用Parallel.For(.)

本文关键字:Parallel For 线程 列表 何填写 | 更新日期: 2023-09-27 18:01:45

假设我有一个有很多属性的学生的class,让我们把它简化成这样:

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。对于,我可以想象这样做:

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);
});

实现并行的正确方法是什么?因为在上面描述的事情中?我是否应该在添加之前锁定列表,具体如何锁定?

@Edit 15:52 09-07-2015

下面答案的结果如下(524条记录):

  • 2:09分钟-正常循环
  • 0:19分钟- AsParallel loop

如何填写列表< >在主线程上使用Parallel.For(.)

我宁愿使用PLinq而不是添加到List<T>(这不是线程安全的):

List<Student> allStudents = Enumerable
  .Range(startRow, endRow - startRow)
  .AsParallel()
  .Select(i => new Student(...))
  .ToList();