我使用ConcurrentDictioanry<string, HashSet<string>>
來訪問跨多個線程的一些數據。AddOrUpdate時鎖定ConcurrentDictionary?
我在this article(向下滾動)中看到方法AddOrUpdate
沒有在鎖中執行,所以它可能危及線程安全。
我的代碼如下:
//keys and bar are not the concern here
ConcurrentDictioanry<string, HashSet<string>> foo = new ...;
foreach(var key in keys) {
foo.AddOrUpdate(key, new HashSet<string> { bar }, (key, val) => {
val.Add(bar);
return val;
});
}
我應該附上一個lock
聲明AddOrUpdate
調用,以確保一切是線程安全的?
如果通過API訪問(讀寫)「ConcurrentDictionary」實例,該怎麼辦?所以客戶端代碼實際上並不會注意到有'ConcurrentDictionary',那麼我可以安全地在我的API的公共方法中進行鎖定,對吧?我只是努力去理解這裏的東西...... – Paul
@Paul:是的,你*可以*確保你每次訪問任何東西時都會鎖定。但是那麼你認爲ConcurrentDictionary真的會買你什麼? –
是的,你說得對。 – Paul