gpt4 book ai didi

c# - 在 Parallel.ForEach 之外设置断点时列表计数无效

转载 作者:太空宇宙 更新时间:2023-11-03 10:41:24 28 4
gpt4 key购买 nike

据我了解,在使用 TPL Parallel.ForEach 时,我们不需要显式编写代码来“等待”其中的任务完成。但是,我正在将 1000 个元素从源列表简单地传输到目标列表中。在 Parallel.ForEach 循环之外和之后设置断点时,我看到目标列表中的项目计数无效/不完整...为什么?

List<int> myList = new List<int> { };
for (int i = 0; i < 1000; i++) {
myList.Add(i);
}
List<int> newList = new List<int>();
Parallel.ForEach(myList, x => {
newList.Add(x);
});
Thread.Sleep(5000);
var test = newList.Count;

最佳答案

List 不是线程安全的,因此您不能在并行代码中使用它。你应该使用 ConcurrentBag (或任何其他线程安全的集合)改为:

var bag = new ConcurrentBag<int>();
Parallel.ForEach(myList, x =>
{
bag.Add(x);
});

您也可以在 newList 周围使用 lock,但这会使并行化变得无用。

关于c# - 在 Parallel.ForEach 之外设置断点时列表计数无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25222054/

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