我们可以使用Parallel.ForEach()将新元素添加到列表中吗? [英] Can we add new elements to a list using Parallel.ForEach()?
问题描述
我的代码做了很简单的事情
My code does very simple stuff
列表已包含元素.我在列表中大约有25000个元素(并且我希望有更多),每个元素都很小(DateTime).
list already has elements. I have approximately 25000 elements (and I'm expecting to have more) in the list and each element is small (DateTime).
List<DateTime> newList = new List<DateTime>();
Parallel.ForEach(list, l => newlist.Add(new DateTime(l.Ticks + 5000)));
即,根据每个元素,我正在创建新元素并将其添加到其他列表中. 但是,这似乎不是一个好的编程方法.我 一些 遇到了这种例外,但并非每次都如此.
i.e, based on each element, I'm creating new elements and adding them to a different list. But, this doesn't seem to be a good programming approach. I hit this exceptions some times, but not everytime.
IndexOutOfRangeException : {"Index was outside the bounds of the array."}
我们可以使用Parallel.ForEach()将元素添加到列表中吗?如果是,为什么我会出现错误?如果没有,为什么?
Can we add elements to a list using Parallel.ForEach()? If yes, why do I hit the error? If no, why?
推荐答案
在这种情况下,您真正想要的是这样的东西:
What you would really want in this situation is more like this:
newlist = list.AsParallel().Select(l => new DateTime(l.Ticks + 5000)).ToList();
尽管您应该衡量性能,以查看这种情况是否还受益于并行化.
Although you should measure the performance to see if this situation even benefits from parallelization.
这篇关于我们可以使用Parallel.ForEach()将新元素添加到列表中吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!