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