tags:

views:

123

answers:

2

Hi,

I have a sorted dictionary, which stores some data. Every two minutes or so I do the following:

sorteddcitionary.Values.ToList() ----> This line throw exception sometimes. It is not consistent. The exception is as follows:

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)

Any idea why this exception is coming from .Net LINQ code ?

It is within a lock. I am posting the code snippet. (This is after bzlm's response.)

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)
{}
+2  A: 

It could be that the collection is being modified at the same time as it is being iterated. If this code is accessed by more than one thread simultaneously, you might need to lock the list for modifications while iterating it.

bzlm
No, it is within a lock. I have updated my question after seeing your response.
Prashant
Please show how `locker` is defined. Also, my concern was that code *elsewhere* modifies `MessageCache`; is there no risk of that?
bzlm
+1  A: 

Locking during the ToList is not sufficient. You must also lock (the same object!) during the modification.

David B