我們有一個非常嚴重的問題,每分鐘造成數千例外。我們已經有了運行在的形式保存數據的本土緩存機制網站:.net Dictionary.Resize()異常 - 線程安全嗎?
protected static IDictionary<int, IList<IInterfaceForData>> m_Data = null;
當我們調用添加這個字典中,我們得到了一個非常奇怪的現象:「指數外
if(Monitor.TryEnter(m_LockObj, 1000))
{
try
{
m_Data.Add(id, new List<IInterfaceForData>());
}
catch(Exception ex)
{
// log exception
}
finally
{
Monitor.Exit(m_LockObj);
}
}
:
m_Data.Add(id, new List<IInterfaceForData>());
我們使用這樣的鎖保護這一呼籲:數組」,當關鍵是100%沒有在字典中的邊界我們得到這個異常:
at System.Collections.Generic.Dictionary`2.Resize() at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add) at System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value)
我們找不到任何解釋這是因爲異常有關詞典的線程安全的,我們(我們認爲)是線程安全的。我們對每個Add()和Remove()調用使用lock()或Monitor.TryEnter,除了m_Data.TryGetValue(...)
任何幫助將不勝感激。
非常感謝。
您還必須鎖定'TryGetValue',以及讀取或更新字典的其他內容。當某個其他線程同時添加或刪除一個項目時,TryGetValue'傾向於表現不可預知的行爲。 – 2011-03-02 21:05:12
也許你正在將* generic *字典上的'TryGetValue'與* concurrent *字典上的TryGetValue混淆,因爲它們都是最近才引入的(.NET 3.5和.NET 4)。 – Justin 2011-03-02 21:19:20
@Justin:哇? '詞典 .TryGetValue'已經存在了! –
2011-03-02 22:41:50