热线(9:00-18:00):13544706711
当前位置: 首页 > 教程技巧 > 

c# Cache 使用实例

时间: 2018/09/29 09:02:08

        /// 
        /// 创建缓存项的文件
        /// 
        /// 缓存Key
        /// object对象
        public static void Insert(string key, object obj)
        {
            //创建缓存 
            HttpContext.Current.Cache.Insert(key, obj);
        }
        /// 
        /// 移除缓存项的文件
        /// 
        /// 缓存Key
        public static void Remove(string key)
        {
            //创建缓存
            HttpContext.Current.Cache.Remove(key);
        }
        /// 
        /// 创建缓存项的文件依赖
        /// 
        /// 缓存Key
        /// object对象
        /// 文件绝对路径
        public static void Insert(string key, object obj, string fileName)
        {
            //创建缓存依赖项
            CacheDependency dep = new CacheDependency(fileName);
            //创建缓存
            HttpContext.Current.Cache.Insert(key, obj, dep);
        }

        /// 
        /// 创建缓存项过期
        /// 
        /// 缓存Key
        /// object对象
        /// 过期时间(分钟)
        public static void Insert(string key, object obj, int expires)
        {
            HttpContext.Current.Cache.Insert(key, obj, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, expires, 0));
        }

        /// 
        /// 获取缓存对象
        /// 
        /// 缓存Key
        /// object对象
        public static object Get(string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                return null;
            }
            try
            {
                return HttpContext.Current.Cache.Get(key);
            }
            catch
            {
                return null;
            }
        }

        /// 
        /// 获取缓存对象
        /// 
        /// T对象
        /// 缓存Key
        /// 
        public static T Get(string key)
        {
            object obj = Get(key);
            return obj == null ? default(T) : (T)obj;
        }

      

        /// 
        /// 获取数据缓存
        /// 
        /// 
        public static object GetCache(string CacheKey)
        {
            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            return objCache[CacheKey];
        }

        /// 
        /// 设置数据缓存
        /// 
        public static void SetCache(string CacheKey, object objObject)
        {
            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            objCache.Insert(CacheKey, objObject);
        }

        /// 
        /// 移除指定数据缓存
        /// 
        public static void RemoveAllCache(string CacheKey)
        {
            System.Web.Caching.Cache _cache = HttpRuntime.Cache;
            _cache.Remove(CacheKey);
        }

        /// 
        /// 移除全部缓存
        /// 
        public static void RemoveAllCache()
        {
            System.Web.Caching.Cache _cache = HttpRuntime.Cache;
            IDictionaryEnumerator CacheEnum = _cache.GetEnumerator();
            while (CacheEnum.MoveNext())
            {
                _cache.Remove(CacheEnum.Key.ToString());
            }
        }