【发布时间】:2014-11-21 03:32:57
【问题描述】:
我有以下代码,不知何故昨天晚上它抛出了很多异常:
引发了“System.Web.HttpUnhandledException”类型的异常。 ---> System.IndexOutOfRangeException:索引超出了数组的范围。 at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
我只是不明白这是怎么可能的,我检查 null 以及密钥是否可用。这是唯一使用 lastTimeoutCheck 的方法。
private static Dictionary<string, DateTime> lastTimeoutCheck;
private static readonly object CacheLock = new object();
private static void CheckTimeout(string groupName)
{
if (lastTimeoutCheck == null)
{
lastTimeoutCheck = new Dictionary<string, DateTime>();
return;
}
if (!lastTimeoutCheck.ContainsKey(groupName))
{
lastTimeoutCheck.Add(groupName, DateTime.UtcNow);
return;
}
if (lastTimeoutCheck[groupName] <
DateTime.UtcNow.AddMinutes(-GroupConfigSection.TimeOutCheckMinutes))
{
lock (CheckLock)
{
if (lastTimeoutCheck[groupName] <
DateTime.UtcNow.AddMinutes(-GroupConfigSection.TimeOutCheckMinutes))
{
GroupHolder groupHolder =
(GroupHolder) System.Web.HttpContext.Current.Cache.Get(groupName);
if (groupHolder != null)
{
groupHolder.UpdateTime();
}
lastTimeoutCheck[groupName] = DateTime.UtcNow;
}
}
}
}
【问题讨论】:
-
你是在多线程中使用这个方法吗?
Dictionary<,>不是线程安全的。 -
如果您查看错误消息,您会看到错误发生在
Dictionary<Tkey, Tvalue>.Insert()。您确定groupName的值有效吗? -
@JonSkeet 我不使用任何线程。
-
@BvdVen 那么为什么要锁定
CheckLock? -
the code executed while an other user is already running the code所以你有多个线程!
标签: c# exception dictionary static