现在的位置: 首页 > 综合 > 正文

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

2012年10月13日 ⁄ 综合 ⁄ 共 2581字 ⁄ 字号 评论关闭
    public class StaticCacheTest
    {
        private static IDictionary<stringobject> _dic; 
        private static object locker = new object(); 
        
        private static IDictionary<stringobject> CachedDic
        {
            get
            {
                if (_dic == null)
                {
                    lock (locker)
                    {
                        if (_dic == null)
                        {
                            _dic = new Dictionary<stringobject>();
                        }
                    }
                }

                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. HttpContext.Current.Application:整个应用程序都可以共享的,当然存储的时候应该加锁的。
  2.  HttpRuntime.Cache与HttpContext.Current.Cache:二者其实是指向的同一对象,区别在于HttpContext与HttpRuntime的实现上。HttpContext必需是Asp.net的上下文中使用,而HttpRuntime则可以在任何上下文中使用,例如可以在控制台程序中利用HttpRuntime作为缓存。
  3. 静态变量的方式:本质上与HttpRuntime.Cache的实现原理是一样的(Cache的也是静态变量)。

    第1与第3只适合存储少量数据(小于1M),否则性能上会有损失。而HttpRuntime.Cache则在内存的使用效率上和功能上(例如缓存依赖、过期策略等)都有所增强,所以应该在实际应用中尽量使用它。

【上篇】
【下篇】

抱歉!评论已关闭.