具有如下:並行執行調用方法線程安全
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;
}
- 由於每個人得到更新的「分開」,自己單獨的線程和一個無關另一個,確實AddAge()方法必須是線程安全的?
- CLR是否爲每個線程執行它自己的「AddAge()」副本 - 使它在線程之間分開?
'通過引用'你沒有通過任何引用該行的任何東西。另外,你的'AddAge'計算一個數字,然後將它放在地板上;它實際上並沒有對它創建的數字做任何事情(不會編譯)。 – Servy
人是一種參考類型。所以當它到達AddAge時,它會發送一個對該對象的引用。不是嗎? – BobSwanson
變量的值是一個參考。該變量是通過值傳遞,而不是通過引用。 – Servy