2010-02-15 89 views
4

我有一個排序字典,它存儲了一些數據。每隔兩分鐘左右,我做到以下幾點:.ToList拋出異常

sorteddcitionary.Values.ToList()---->這一行,有時拋出異常。這是不一致的。例外如下:

System.IndexOutOfRangeException: Index was outside the bounds of the array. 

at System.Collections.Generic.SortedDictionary`2.ValueCollection.<>c__DisplayClass11.CopyTo>b__10(Node node) 
at System.Collections.Generic.TreeSet`1.InOrderTreeWalk(TreeWalkAction`1 action) 
at System.Collections.Generic.SortedDictionary`2.ValueCollection.CopyTo(TValue[] array, Int32 index) 
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) 
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source) 
at Aditi.BMCMUtility.UnModCacheMaster.MessageAddition(PrivateMessage message, Nullable`1 cnt) 

任何想法爲什麼這個異常來自.NET LINQ代碼?

它處於鎖定狀態。我發佈了代碼片段。 (這是在bzlm的響應之後)。

try 
{ 
    lock (locker) 
    { 
     MessageCache.Add(message.MessageID, message); 
     privMsgList = MessageCache.Values.ToList(); /// Line which throws exception 
     while (MessageCache.Count > cnt.Value) 
     { 
      MessageCache.Remove((MessageCache.First().Key)); 
     } 
    } 
} 
catch(Exception ex) 
{} 

回答

4

它可能是因爲它正在被迭代的同時被修改。如果此代碼被多個線程同時訪問,則可能需要在迭代時鎖定列表以進行修改。

+0

不,它處於鎖定狀態。在看到您的回覆後,我已更新了我的問題。 – Prashant 2010-02-15 10:15:07

+0

請顯示'locker'是如何定義的。另外,我擔心的是代碼*在其他地方修改了「MessageCache」;這沒有風險嗎? – bzlm 2010-02-15 15:52:35

1

的ToList過程中的鎖定是不夠的。在修改過程中,您還必須鎖定(同一個對象!)。