question

TZacks-2728 avatar image
0 Votes"
TZacks-2728 asked TZacks-2728 answered

Iterate List<T> with Parallel.ForEach

see my code and tell can i use this code in production ?
any chances is there in below code that overlapping of data ?

 private void button3_Click(object sender, EventArgs e)
         {
             List<Person> persons = GetPerson();
             var persons1 = new List<Person>();
             var locker = new object();
             Parallel.ForEach(
                 persons,
                 () => new List<Person>(), // initialize aggregate per thread 
                 (person, loopState, subtotal) =>
                 {
                     subtotal.Add(person); // add current thread element to aggregate 
                     return subtotal; // return current thread aggregate
                 },
                 p => // action to combine all threads results
                 {
                     lock (locker) // lock, cause List<T> is not a thread safe collection
                     {
                         persons1.AddRange(p);
                     }
                 }
             );
         }

         private List<Person> GetPerson()
         {
             List<Person> p = new List<Person>
             {
                 new Person() { Id = 0, Name = "Artur", Age = 5 },
                 new Person() { Id = 1, Name = "Edward", Age = 10 },
                 new Person() { Id = 2, Name = "Krzysiek", Age = 20 },
                 new Person() { Id = 3, Name = "Piotr", Age = 15 },
                 new Person() { Id = 4, Name = "Adam", Age = 10 }
             };
    
             return p;
         }


Thanks

dotnet-csharp
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

TZacks-2728 avatar image
1 Vote"
TZacks-2728 answered

Issue resolved.

  var persons1 = new List<Person>();
  var locker = new object();
  Parallel.ForEach(
      persons,
      () => new List<Person>(), // initialize aggregate per thread 
      (person, loopState, subtotal) =>
      {
          subtotal.Add(person); // add current thread element to aggregate 
          return subtotal; // return current thread aggregate
      },
      p => // action to combine all threads results
      {
          lock (locker) // lock, cause List<T> is not a thread safe collection
          {
              persons1.AddRange(p);
          }
      }
  );
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.