2010-02-15 7 views
4

나는 어떤 자료를 저장하는 분류 된 사전이있다. 2 분마다 다음을 수행합니다..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

+0

'사물함'이 정의 된 방법을 보여주십시오. 또한, 내 관심사는 * 다른 곳에서 * MessageCache를 수정 한 것입니다. 그 위험은 없습니까? – bzlm

1

ToList를 잠그는 것만으로는 충분하지 않습니다. 수정하는 동안 잠금 (동일한 객체!)도해야합니다.

관련 문제