BobSwanson BobSwanson - 2 months ago 6
C# Question

Parallel execution calling a method thread safety

Having the following:

List<Person> persons = // list of persons
Parallel.ForEach(persons, (i) => {
AddAge(i);
});

// Does this method needs to be thread safe?
// Why?
public void AddAge(Person person)
{
// Multiple threads execute here at once. However they're
// working with their own "person" object, therefore
// each thread won't corrupt others "person" object - is this assumption correct?
person.Age =+ 10;
}



  • Since each person gets updated "separately" on their own separate threads and one has nothing to do with another, does AddAge() method have to be thread safe?

  • Does CLR executes it's own copy of "AddAge()" per thread - making it separate between threads?


Answer

Thread safety relates to modifying the same data from multiple threads. If you are operating on separate data (such as your Parallel.ForEach) and are properly gating your work so that batches are completed before dependant work you do not need thread safe code within, as you are doing your thread safety outside the method (by ensuring each thread gets its own set of data to work with).

Comments