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了,對於全域儲存一些東西的機制居然也都搞不清了,今天特意做個測實驗證一下,做個記錄供自己以後參考,記錄如下:
- HttpContext.Current.Application:整個應用程式都可以共用的,當然儲存的時候應該加鎖的。
- HttpRuntime.Cache與HttpContext.Current.Cache:二者其實是指向的同一對象,區別在於HttpContext與HttpRuntime的實現上。HttpContext必需是Asp.net的上下文中使用,而HttpRuntime則可以在任何上下文中使用,例如可以在控制台程式中利用HttpRuntime作為緩衝。
- 靜態變數的方式:本質上與HttpRuntime.Cache的實現原理是一樣的(Cache的也是靜態變數)。
第1與第3隻適合儲存少量資料(小於1M),否則效能上會有損失。而HttpRuntime.Cache則在記憶體的使用效率上和功能上(例如緩衝依賴、到期策略等)都有所增強,所以應該在實際應用中盡量使用它。