Asp.Net中可以方便的使用緩衝,對於Cache,一般有兩種方式調用:HttpContext.Cache和HttpRuntime.Cache。那麼這兩種Cache有什麼區別呢?
先來看看Msdn上的注釋:
HttpRuntime.Cache:擷取當前應用程式的 Cache。
HttpContext.Cache:為當前 HTTP 請求擷取 Cache 對象。
那麼是不是說對於HttpRuntime.Cache就是應用程式級,而HttpContext.Cache則是針對每個使用者的呢?NO,而實際上,兩者調用的是同一個對象。他們的區別僅僅在於調用方式不一樣(就我所知)。
事實勝過雄辯,寫個例子來證實一下:
/**//// <summary> /// 通過HttpRuntime.Cache的方式來儲存Cache /// </summary> private void btnHttpRuntimeCacheSave_Click(object sender, System.EventArgs e) ...{ HttpRuntime.Cache.Insert(cacheKey, cacheValue, null, DateTime.Now.AddMinutes(3), TimeSpan.Zero); } /**//// <summary> /// 通過HttpRuntime.Cache的方式來讀取Cache /// </summary> private void btnHttpRuntimeCacheLoad_Click(object sender, System.EventArgs e) ...{ if (HttpRuntime.Cache[cacheKey] == null) ...{ cacheContent = "No Cache"; } else ...{ cacheContent = (string)HttpRuntime.Cache[cacheKey]; } lblCacheContent.Text = cacheContent; } /**//// <summary> /// 通過HttpContext.Cache的方式來儲存Cache /// </summary> private void btnHttpContextCacheSave_Click(object sender, System.EventArgs e) ...{ HttpContext.Current.Cache.Insert(cacheKey, cacheValue, null, DateTime.Now.AddMinutes(3), TimeSpan.Zero); } /**//// <summary> /// 通過HttpContext.Cache的方式來讀取Cache /// </summary> private void btnHttpContextCacheLoad_Click(object sender, System.EventArgs e) ...{ if (HttpContext.Current.Cache[cacheKey] == null) ...{ cacheContent = "No Cache"; } else ...{ cacheContent = (string)HttpContext.Current.Cache[cacheKey]; } lblCacheContent.Text = cacheContent; }
通過這個例子可以很容易證明:
- HttpContext.Cache儲存的Cache,HttpContext.Cache和HttpRuntime.Cache都可以讀取。
- HttpRuntime.Cache儲存的Cache,HttpContext.Cache和HttpRuntime.Cache都可以讀取。
- 無論是哪個使用者通過什麼方式對Cache的改變,其他使用者無論用什麼方式讀取的Cache內容也會隨之變。
HttpRuntime.Cache 相當於就是一個緩衝具體實作類別,這個類雖然被放在了 System.Web 命名空間下了。但是非 Web 應用程式也是可以拿來用的(其它類型也可以用,如控制台等)。
HttpContext.Cache 是對上述緩衝類的封裝,由於封裝到了 HttpContext ,局限於只能在知道 HttpContext 下使用,即只能用於 Web 應用程式。