可以在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;
??????????? }
??????? }
??? }
}
轉載于:https://www.cnblogs.com/uruz7/archive/2010/07/29/1787480.html
總結
以上是生活随笔為你收集整理的可以在Silverlight中使用的,支持定时自动回收的缓存类(C# 代码)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ASP.NET两个关联的表的增删查改
- 下一篇: 1.MVC的工作流程