1

On using SomeCollection.AsParallel().ForAll(), the count of the resulted collection is less when compared to the actual input collection

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());
});

Excepting the count of someCollection should be equal to resultCollection1 and resultCollection2

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
Loozer
  • 21
  • 3
  • `List` and by association `List.Add` is not threadsafe. See - https://stackoverflow.com/questions/5589315/list-add-thread-safety. As such, when running multiple add operations the results are not correct. – Kami Sep 13 '19 at 14:02

1 Answers1

1

Well, List<T> is not thread safe, however using the ForAll method you can try to modify same List<T> by several threads:

   someCollection
     .AsParallel()
     .ForAll(x => {
        // now resultCollection1 is modifying by several threads
        resultCollection1.Add(x.ToString()); 
      });

Put it as (existing collection modification)

   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())); 

Or (creating a new collection)

   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();  
Mauricio Gracia Gutierrez
  • 10,288
  • 6
  • 68
  • 99
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215