I have the following code, and somehow yesterday evening it had thrown a lot of exceptions:
Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.IndexOutOfRangeException: Index was outside the bounds of the array. at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
I just don't see how this is possible, I check for null and if the key is available. This is the only method where lastTimeoutCheck is used.
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<,>
is not thread-safe. – Jon SkeetDictionary<Tkey, Tvalue>.Insert()
. Are you sure thatgroupName
has a valid value? – JLRisheCheckLock
? – Guillaumethe code executed while an other user is already running the code
So you have multiple threads ! – Guillaume