Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill a List<T> on the main-thread using Parallel.For(..)

Imagine I have got the following Class for a student with lots of properties, lets simplify it to this:

public class Student{
    public Int64 id { get; set; }
    public String name { get; set; }
    public Int64 Age { get; set; }
}

Then on the main-thread I have got the following List:

List<Student> allStudents = new List<Student>();

Say I have 500 students in an Excel file and I want to gather them and insert them in the list. I can do something as follows:

for(int i = startRow; i < endRow; i++){
    Student s = new Student();

    //Perform a lot of actions to gather all the information standing on the row//

    allStudents.Add(s);
}

Now because gathering the information in Excel is very slow, because numerous actions have to be performed. So I want to use Parallel.For, I can imagine to do the following:

Parallel.For(startRow, endRow, i => {
    Student s = new Student();

    //Perform a lot of actions to gather all the information standing on the row//

    //Here comes my problem. I want to add it to the collection on the main-thread.
    allStudents.Add(s);
});

What is the correct way to implement Parallel.For in the matter described above? Should I lock the list before adding and how exactly?

@Edit 15:52 09-07-2015

The results of the answer below are as follows (524 records):

  • 2:09 minutes - Normal loop
  • 0:19 minutes - AsParallel loop
like image 250
Revils Avatar asked Jan 08 '23 00:01

Revils


1 Answers

I'd rather use PLinq instead of adding to List<T> (which is not thread safe):

List<Student> allStudents = Enumerable
  .Range(startRow, endRow - startRow)
  .AsParallel()
  .Select(i => new Student(...))
  .ToList();
like image 151
Dmitry Bychenko Avatar answered Jan 15 '23 07:01

Dmitry Bychenko