C#中对于缓存Cache的使用

2025-05-10 20:41:11

1、引入:using System.Web.Caching;命名空间

2、增加缓存添加方法:/// <summary> /// /// </summary> /// <param name租涫疼迟="key">缓存key,全局唯一</param> /// <param name="value">缓存值</param> /// <param name="minutes">缓存时间(分钟)</param> /// <param name="useAbsoluteExpiration">是否绝对过期</param> public static void Add(string key, object value, int minutes, bool useAbsoluteExpiration) { if (key != null && value != null) { if (useAbsoluteExpiration) { HttpContext.Current.Cache.Insert(key, value, null, DateTime.Now.AddMinutes(minutes), Cache.NoSlidingExpiration); } else { HttpContext.Current.Cache.Insert(key, value, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, minutes, 0)); } } }

3、增加移除缓存的方法:public static object Remove(string key) { return HttpContext.Current.Cache.Remove(key); }

4、增加移除全部缓存的方法:public static void RemoveAll() { System.Web.Caching.Cache _cach髫潋啜缅e = HttpRuntime.Cache; System.Collections.IDictionaryEnumerator CacheEnum = _cache.GetEnumerator(); if (CacheEnum == null) return; while (CacheEnum.MoveNext()) { Remove(CacheEnum.Key.ToString()); } }

5、在使用缓存的地方,直接调用以上方法即可。

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢