可以在Silverlight中使用的,支持定时自动回收的缓存类(C# 代码)

这些日子主要的经历都放在微软的 私有云private cloud 动态数据中心Dynamic Data Center 项目上。

关于private cloud 和 Dynamic Data Center是什么,今天就不在这里说了。
最近调试的是 DDC V2 的代码。

代码前台的Silverlight使用了 SL4,RIA。很好。但是发现界面控件之间的重复调用还是很多的。我想在Silverlight的项目中,这种情况还是很多见的。
对付重复调用,考虑使用缓存解决问题。结合我们项目的需求和RIA本身的构架,我还是选择了把缓存放在Silverlight的客户端。
采用超时自动回收的机制,既能实现缓存,又能自动刷新。

本来,英哥给我推荐了Enterprise Library里的缓存。但是发现Silverlight里面不能用。

找了找,没找到。还是决定自己写一个简单的。在网上看到好多人写了,把对象缓存至IsolateStorage里去。
但是想了想,由于缓存在客户端,所以被缓存的对象数目有限,还是就放内存了,写个机制自动清空就行了。

特殊一些的就是可以在添加缓存对象的时候传入一个时间,时间一到,自动回收。回收后,再调用的时候就返回null啦。
正好符合我的要求,哈哈。

最后还是自己写了个简单的类。

下面是代码:

using System;
using System.Collections.Generic;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Browser;

namespace SilverlightCache
{
    public class SLCacheWithAutoRecycle
    {
        static Dictionary<string, object> cacheList = new Dictionary<string, object>();
        static Dictionary<System.Windows.Threading.DispatcherTimer, string> timerList = new Dictionary<System.Windows.Threading.DispatcherTimer, string>();

        public static void Add(string key, object value, int recycleTimeInSecond)
        {
            if (!cacheList.ContainsKey(key))
            {
                cacheList.Add(key, value);
                System.Windows.Threading.DispatcherTimer recycleTimer = new System.Windows.Threading.DispatcherTimer();
                timerList.Add(recycleTimer, key);
                recycleTimer.Tick += new EventHandler(recycle);
                recycleTimer.Interval = new TimeSpan(0, 0, recycleTimeInSecond);
                recycleTimer.Start();
            }
        }

        public static void Remove(string key)
        {
            if (cacheList.ContainsKey(key))
            {
                cacheList[key] = null;
                cacheList.Remove(key);
            }
        }

        public static object Get(string key)
        {
            if (cacheList.ContainsKey(key))
            {
                return cacheList[key];
            }
            return null;
        }

        private static void recycle(object o, EventArgs e)
        {
            string key = timerList[(System.Windows.Threading.DispatcherTimer)o];
            Remove(key);
            removeTimer((System.Windows.Threading.DispatcherTimer)o);
        }

        private static void removeTimer(System.Windows.Threading.DispatcherTimer timer)
        {
            if (timerList.ContainsKey(timer))
            {
                timerList.Remove(timer);
                timer.Stop();
                timer = null;
            }
        }
    }
}

posted on 2010-07-29 01:16  史维  阅读(991)  评论(2编辑  收藏  举报

导航