我有以下代码,但昨晚它突然抛出了很多异常:
我不明白这是如何可能的,我检查了空值和键是否可用。这是唯一使用lastTimeoutCheck的方法。引发了类型为'System.Web.HttpUnhandledException'的异常。 ---> System.IndexOutOfRangeException: 索引超出了数组界限。 at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
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<,>
不是线程安全的。 - Jon Skeet