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):
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With