开发者

.ToList throwing exception

I have a sorted dictionary, which st开发者_开发知识库ores 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)
{}


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜