I just saw following code snippet:
public List<string> ProcessText(List<student> students)
{
List<student> result = new();
Parallel.ForEach(students, (st) =>
{
if (string.IsNullOrEmpty(st.Name))
{
throw new Exception("Name cannot be empty");
}
result.Add(st);
});
return result;
}
It got me thinking since the Parallel.ForEach
will distribute the given method arguments i.e.students, between different threads, it doesn't need any synchronization when it wanted add object into the list, for example using lock
or concurrent collection instead of List<T>
?
Now consider we change the code like this:
public List<string> ProcessText(List<student> students)
{
List<student> result = new();
Parallel.ForEach(students, (st) =>
{
if (result.Any(x=>x.Name == st.Name))
{
// do some thing and ignore the rest of the code and go for the next student
}
if (string.IsNullOrEmpty(st.Name))
{
throw new Exception("Name cannot be empty");
}
result.Add(st);
});
return result;
}
Now it refers to the List<student>
and read some values inside of it, so it needs synchronization? And why?
Thanks in advance