.ToList throwing exception

I have a sorted dictionary that stores some data. Every two minutes I do the following:

sorteddcitionary.Values.ToList () ----> This line sometimes throws an exception. This is consistent. An exception is the following:

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 comes from .Net LINQ code?

It is located inside the castle. I am posting a piece of code. (This is after bzlm's answer.)

 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
source share
2 answers

Maybe the collection changes at the same time as it repeats. If this code is accessed by several threads at the same time, you may need to block the list to make changes during iteration.

+4
source

The lock during the ToList list is insufficient. You must also block (the same object!) During the modification.

+1
source

Source: https://habr.com/ru/post/1301304/


All Articles