首页 > 解决方案 > 当我尝试将 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

标签: c#multithreading

解决方案


好吧,List<T>不是线程安全的,但是 使用该方法您可以尝试通过多个线程进行修改:ForAllList<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();  

推荐阅读