c# - 当我尝试将 AsParallel 与集合一起使用时,记录的数量会减少。我在这里想念什么?
问题描述
在使用 SomeCollection.AsParallel().ForAll() 时,与实际输入集合相比,结果集合的计数更少
List<int> someCollection = new List<int>{1,2,3,4,5,6,7,8,9,10};
List<string> resultCollection1 = new List<string>();
List<string> resultCollection2 = new List<string>();
// Using AsParallel - Results in incorrect result
someCollection.AsParallel().ForAll(x => {
resultCollection1 .Add(x.ToString());
});
// Using ForEach - Results in correct result
someCollection.ForEach(x => {
resultCollection2 .Add(x.ToString());
});
除了 someCollection 的计数应该等于 resultCollection1 和 resultCollection2
解决方案
好吧,List<T>
不是线程安全的,但是 使用该方法您可以尝试通过多个线程进行修改:ForAll
List<T>
someCollection
.AsParallel()
.ForAll(x => {
// now resultCollection1 is modifying by several threads
resultCollection1.Add(x.ToString());
});
把它作为(现有集合修改)
List<int> someCollection = new List<int>{1,2,3,4,5,6,7,8,9,10};
List<string> resultCollection = new List<string>();
resultCollection
.AddRange(someCollection
.AsParallel()
.Select(x => x.ToString()));
或者(创建一个新集合)
List<int> someCollection = new List<int>{1,2,3,4,5,6,7,8,9,10};
List<string> resultCollection = someCollection
.AsParallel()
.Select(x => x.ToString())
.ToList();
推荐阅读
- angular - 条件脚本包含取决于环境
- python-3.x - 如何修复“找不到满足要求 bleu 的版本(来自版本:)找不到 bleu 的匹配分发”错误
- hadoop - 放:意外的URISyntaxException
- python - 使用 try 和 except 跳过文件
- c# - ZipArchive 在来自 web 服务的列表中创建无效的 zip 文件
- iar - 如何更改 IAR Workbench 以使用深色主题?
- vb.net - 在两个或多个文本框中重复字符 VB Net
- javascript - 什么可能导致表单输入间歇性不可点击,即不可聚焦
- java - 如何在分布式环境中的 Web 应用程序中查找网页的点击次数
- ios - 在swift中使用Segue时如何显示标签栏