What is the best way to lock cache in asp.net?

前端 未结 10 708
悲&欢浪女
悲&欢浪女 2020-11-27 09:33

I know in certain circumstances, such as long running processes, it is important to lock ASP.NET cache in order to avoid subsequent requests by another user for that resourc

10条回答
  •  [愿得一人]
    2020-11-27 10:12

    Just to echo what Pavel said, I believe this is the most thread safe way of writing it

    private T GetOrAddToCache(string cacheKey, GenericObjectParamsDelegate creator, params object[] creatorArgs) where T : class, new()
        {
            T returnValue = HttpContext.Current.Cache[cacheKey] as T;
            if (returnValue == null)
            {
                lock (this)
                {
                    returnValue = HttpContext.Current.Cache[cacheKey] as T;
                    if (returnValue == null)
                    {
                        returnValue = creator(creatorArgs);
                        if (returnValue == null)
                        {
                            throw new Exception("Attempt to cache a null reference");
                        }
                        HttpContext.Current.Cache.Add(
                            cacheKey,
                            returnValue,
                            null,
                            System.Web.Caching.Cache.NoAbsoluteExpiration,
                            System.Web.Caching.Cache.NoSlidingExpiration,
                            CacheItemPriority.Normal,
                            null);
                    }
                }
            }
    
            return returnValue;
        }
    

提交回复
热议问题