c# Cache 使用实例
程序员文章站
2022-12-25 11:49:46
/// /// 创建缓存项的文件 /// /// 缓存Key /// object对象 public static void Insert(string key, object obj) { //创建缓存 HttpContext.C... ......
/// <summary> /// 创建缓存项的文件 /// </summary> /// <param name="key">缓存key</param> /// <param name="obj">object对象</param> public static void insert(string key, object obj) { //创建缓存 httpcontext.current.cache.insert(key, obj); } /// <summary> /// 移除缓存项的文件 /// </summary> /// <param name="key">缓存key</param> public static void remove(string key) { //创建缓存 httpcontext.current.cache.remove(key); } /// <summary> /// 创建缓存项的文件依赖 /// </summary> /// <param name="key">缓存key</param> /// <param name="obj">object对象</param> /// <param name="filename">文件绝对路径</param> public static void insert(string key, object obj, string filename) { //创建缓存依赖项 cachedependency dep = new cachedependency(filename); //创建缓存 httpcontext.current.cache.insert(key, obj, dep); } /// <summary> /// 创建缓存项过期 /// </summary> /// <param name="key">缓存key</param> /// <param name="obj">object对象</param> /// <param name="expires">过期时间(分钟)</param> public static void insert(string key, object obj, int expires) { httpcontext.current.cache.insert(key, obj, null, cache.noabsoluteexpiration, new timespan(0, expires, 0)); } /// <summary> /// 获取缓存对象 /// </summary> /// <param name="key">缓存key</param> /// <returns>object对象</returns> public static object get(string key) { if (string.isnullorempty(key)) { return null; } try { return httpcontext.current.cache.get(key); } catch { return null; } } /// <summary> /// 获取缓存对象 /// </summary> /// <typeparam name="t">t对象</typeparam> /// <param name="key">缓存key</param> /// <returns></returns> public static t get<t>(string key) { object obj = get(key); return obj == null ? default(t) : (t)obj; } /// <summary> /// 获取数据缓存 /// </summary> /// <param name="cachekey">键</param> public static object getcache(string cachekey) { system.web.caching.cache objcache = httpruntime.cache; return objcache[cachekey]; } /// <summary> /// 设置数据缓存 /// </summary> public static void setcache(string cachekey, object objobject) { system.web.caching.cache objcache = httpruntime.cache; objcache.insert(cachekey, objobject); } /// <summary> /// 移除指定数据缓存 /// </summary> public static void removeallcache(string cachekey) { system.web.caching.cache _cache = httpruntime.cache; _cache.remove(cachekey); } /// <summary> /// 移除全部缓存 /// </summary> public static void removeallcache() { system.web.caching.cache _cache = httpruntime.cache; idictionaryenumerator cacheenum = _cache.getenumerator(); while (cacheenum.movenext()) { _cache.remove(cacheenum.key.tostring()); } }
上一篇: OpenStack 组件的更新教程