拥有以下内容:
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;
}
答案 0 :(得分:2)
线程安全涉及从多个线程修改相同的数据。如果您正在操作单独的数据(例如您的Parallel.ForEach
)并且正确选择您的工作以便在依赖工作之前完成批处理,则您不需要在其中使用线程安全代码,因为您在方法之外执行线程安全(通过确保每个线程获得自己的一组数据来使用)。