我有一个排序字典,它存储一些数据。每两分钟左右我会做以下事情:
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)
{}
答案 0 :(得分:4)
可能是在迭代的同时修改了集合。如果同时由多个线程访问此代码,则可能需要在迭代时锁定列表以进行修改。
答案 1 :(得分:1)
ToList期间的锁定是不够的。您还必须在修改期间锁定(同一个对象!)。