• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Asp.net中全局缓存的几种方式

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

public class StaticCacheTest

{

private static IDictionary<string, object> _dic;

private static object locker = new object();

 

private static IDictionary<string, object> CachedDic

{

get

{

if (_dic == null)

{

lock (locker)

{

if (_dic == null)

{

_dic = new Dictionary<string, object>();

}

}

}

 

return _dic;

}

}

 

public static object GetObject(string key)

{

return CachedDic[key];

}

 

public static void SetObject(string key, object obj)

{

lock (locker)

{

CachedDic[key] = obj;

}

}

}

 

public partial class _Default : System.Web.UI.Page

{

private const string KEY = "CurrentTime";

 

protected void Page_Load(object sender, EventArgs e)

{

String curTime = System.DateTime.Now.ToString();

if (HttpContext.Current.Application[KEY] == null)

{

HttpContext.Current.Application.Lock();
HttpContext.Current.Application[KEY] = curTime;
HttpContext.Current.Application.UnLock();
}

if (HttpContext.Current.Cache[KEY] == null)

{

HttpContext.Current.Cache.Insert(KEY, curTime);

}

if (StaticCacheTest.GetObject(KEY) == null) //本质上就是HttpRuntime.Cache的实现方式

{

StaticCacheTest.SetObject(KEY, curTime);

}

if (HttpRuntime.Cache[KEY] == null)

{

HttpRuntime.Cache.Insert(KEY, curTime); //HttpRuntime.Cache与HttpContext.Current.Cache是同一对象,建议使用HttpRuntime.Cache

}

 

TextBox1.Text = HttpContext.Current.Application[KEY].ToString();

TextBox2.Text=HttpContext.Current.Cache[KEY].ToString();

TextBox3.Text=StaticCacheTest.GetObject(KEY).ToString();

TextBox4.Text=System.Web.HttpRuntime.Cache.Get(Key).ToString();

}

}

------------------------------------------------------------------------------------------------

System.Web.HttpRuntime.Cache的方法:

Add

Insert

Get

Remove

 

缓存的操作包括:读、写。
读取缓存内容调用System.Web.HttpRuntime.Cache.Get(Key)方法,插入缓存数据调用Add或Insert方法。

 

Add与Insert的不同

HttpRuntime.Cache.Add 存在相同的键会异常,返回缓存成功的对象。

HttpRuntime.Cache.Insert存在相同的键会替换原值,无返回值。

如果您希望某个缓存项目一旦放入缓存后,就不要再被修改,那么调用Add确实可以防止后来的修改操作。而调用Insert方法,则永远会覆盖已存在项。

 

缓存的过期时间

缓存过期时间包括:绝对过期和滑动过期。

绝对过期:到了指定时间以后便会失效。

滑动过期:在指定时间内无访问请求便失效。

实例:

绝对过期:

HttpRuntime.Cache.Insert(key, value, null, DateTime.Now.AddSeconds(seconds),System.Web.Caching.Cache.NoSlidingExpiration);

滑动过期:

HttpRuntime.Cache.Insert(key, value, null, System.Web.Caching.Cache.NoAbsoluteExpiration
, TimeSpan.FromSeconds(seconds));


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
NetWebApiRouteAsp.NetWebApiRoute发布时间:2022-07-10
下一篇:
asp.net链接SQLite数据库通用类与web.config的配置发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap