企业库高速缓存管理器“索引超出了数组的范围”错误

时间:2013-12-10 18:18:59

标签: c# asp.net enterprise-library

我在使用Microsoft Enterprise Library的缓存块进行缓存方面存在间歇性问题,因为从缓存中检索项目时我收到Index was outside the bounds of the array异常。这只是在我们的生产服务器上间歇性地发生,我认为发生的事情是,当cacheManager.Keys.CopyTo(currentCacheKeys, 0);行执行时,缓存管理器密钥已由另一个进程更新,并且上面定义的currentCacheKeys数组不再足以容纳新条目,因此Index was outside the bounds of the array例外。

这是一个合理的假设,是否有人对绕过这个问题的方法有任何建议?我唯一能想到的就是使用object lock type of approach,但我不确定这是否有效,因为我需要锁定什么?

public static string[] GetCacheKeys(int? instanceId)
{
    string[] cacheKeys = null;

    ICacheManager cacheManager = CacheFactory.GetCacheManager();
    if (cacheManager != null)
    {
        int cachedItemCount = cacheManager.Count;
        if (cachedItemCount > 0)
        {
            object[] currentCacheKeys = new object[cachedItemCount];
            cacheManager.Keys.CopyTo(currentCacheKeys, 0);

            if (currentCacheKeys != null && currentCacheKeys.Length > 0)
            {
                ArrayList cacheKeyList = new ArrayList();

                // omitted for brevity

                cacheKeys = (string[])cacheKeyList.ToArray(typeof(string));
            }
        }
    }

    return cacheKeys;
}

堆栈跟踪

Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array.

   at System.Array.InternalGetReference(Void* elemRef, Int32 rank, Int32* pIndices)
   at System.Collections.Hashtable.CopyKeys(Array array, Int32 arrayIndex)
   at ProjectName.Library.Helpers.CacheHelper.GetCacheKeys(Nullable`1 instanceId)
   ...

1 个答案:

答案 0 :(得分:0)

这是由于返回CacheManager密钥时企业库的自定义实现引起的 - 正在发生的事情是存储密钥的数组正在定义,但是当密钥复制到数组上的时间不够大,因为更新的密钥已添加到缓存中。它通过使用传递给CacheManager构造函数的缓存对象的CurrrentCacheState属性来解决,而不是realCache.Keys

    public ICollection Keys
    {
        get { return realCache.CurrentCacheState.Keys; }
    }

请参阅完整说明here