在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
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(); } } 两年多没有搞Asp.net了,对于全局存储一些东西的机制居然也都搞不清了,今天特意做个测试验证一下,做个记录供自己以后参考,记录如下:
第1与第3只适合存储少量数据(小于1M),否则性能上会有损失。而HttpRuntime.Cache则在内存的使用效率上和功能上(例如缓存依赖、过期策略等)都有所增强,所以应该在实际应用中尽量使用它。 |
请发表评论