HttpContext.Cache和HttpRuntime.Cache)

來源:互聯網
上載者:User

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;        }
    通過這個例子可以很容易證明: 

  1. HttpContext.Cache儲存的Cache,HttpContext.Cache和HttpRuntime.Cache都可以讀取。 
  2. HttpRuntime.Cache儲存的Cache,HttpContext.Cache和HttpRuntime.Cache都可以讀取。 
  3. 無論是哪個使用者通過什麼方式對Cache的改變,其他使用者無論用什麼方式讀取的Cache內容也會隨之變。

 

HttpRuntime.Cache 相當於就是一個緩衝具體實作類別,這個類雖然被放在了 System.Web 命名空間下了。但是非 Web 應用程式也是可以拿來用的(其它類型也可以用,如控制台等)。
HttpContext.Cache 是對上述緩衝類的封裝,由於封裝到了 HttpContext ,局限於只能在知道 HttpContext 下使用,即只能用於 Web 應用程式。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.