How can I cache objects in ASP.NET MVC?

后端 未结 8 1045
一生所求
一生所求 2020-12-04 06:25

I\'d like to cache objects in ASP.NET MVC. I have a BaseController that I want all Controllers to inherit from. In the BaseController there is a User

8条回答
  •  旧时难觅i
    2020-12-04 06:44

    Implementation with a minimal cache locking. The value stored in the cache is wrapped in a container. If the value is not in the cache, then the value container is locked. The cache is locked only during the creation of the container.

    public static class CacheExtensions
    {
        private static object sync = new object();
    
        private class Container
        {
            public T Value;
        }
    
        public static TValue GetOrStore(this Cache cache, string key, Func create, TimeSpan slidingExpiration)
        {
            return cache.GetOrStore(key, create, Cache.NoAbsoluteExpiration, slidingExpiration);
        }
    
        public static TValue GetOrStore(this Cache cache, string key, Func create, DateTime absoluteExpiration)
        {
            return cache.GetOrStore(key, create, absoluteExpiration, Cache.NoSlidingExpiration);
        }
    
        public static TValue GetOrStore(this Cache cache, string key, Func create, DateTime absoluteExpiration, TimeSpan slidingExpiration)
        {
            return cache.GetOrCreate(key, x => create());
        }
    
        public static TValue GetOrStore(this Cache cache, string key, Func create, DateTime absoluteExpiration, TimeSpan slidingExpiration)
        {
            var instance = cache.GetOrStoreContainer(key, absoluteExpiration, slidingExpiration);
            if (instance.Value == null)
                lock (instance)
                    if (instance.Value == null)
                        instance.Value = create(key);
    
            return instance.Value;
        }
    
        private static Container GetOrStoreContainer(this Cache cache, string key, DateTime absoluteExpiration, TimeSpan slidingExpiration)
        {
            var instance = cache[key];
            if (instance == null)
                lock (cache)
                {
                    instance = cache[key];
                    if (instance == null)
                    {
                        instance = new Container();
    
                        cache.Add(key, instance, null, absoluteExpiration, slidingExpiration, CacheItemPriority.Default, null);
                    }
                }
    
            return (Container)instance;
        }
    }
    

提交回复
热议问题