I need to process a list of objects (not the same shown on the sample), which I thought could be greatly improved by running it in parallel.foreach loop. However, the result is not what I expected. Sometimes the returned list doesn't match with the input list. Please let me know why it is not working as I expected (novise), and also how to make it work. Please see sample code used below.
List<string> list = new List<string>() { "John", "Mary", "Margaret", "Silvia", "Martha" };
List<Person> people = new List<Person>();
Console.WriteLine("There are {0} names on the list", list.Count.ToString());
Parallel.ForEach(list, name =>
{
people.Add(new Person(name));
});
foreach (Person person in people)
{
Console.WriteLine("Name: {0,-10} Age: {1}", person.Name, person.Age.ToString());
}
Console.WriteLine("There are {0} people on the list", people.Count.ToString());
Console.ReadLine();
namespace ParallelForEach
{
internal class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Person(string name)
{
Name = name;
Age = name.Sum(c => (int)c);
}
}
}