并行执行调用方法线程安全

Parallel execution calling a method thread safety

具有以下特征:

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;
}

线程安全涉及从多个线程修改相同的数据。如果您正在对单独的数据(例如您的 Parallel.ForEach)进行操作,并且正在正确地控制您的工作,以便在依赖工作之前完成批处理,那么您不需要内部的线程安全代码,因为您在方法之外进行线程安全(通过确保每个线程都有自己的数据集来处理)。