gpt4 book ai didi

c# - 如何使用 Parallel.For(..) 在主线程上填充 List

转载 作者:太空狗 更新时间:2023-10-30 00:23:59 25 4
gpt4 key购买 nike

想象一下,我为一个具有很多属性的学生创建了以下类,让我们将其简化为:

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 的正确实现方式是什么?我应该在添加之前锁定列表吗?具体如何锁定?

@Edit 2015 年 9 月 7 日 15:52

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

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

最佳答案

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

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

关于c# - 如何使用 Parallel.For(..) 在主线程上填充 List<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31318292/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com