轉載自:http://blog.csdn.net/mss359681091/article/details/51076712
本文導讀:在.NET運用中經常用到緩存(Cache)對象。有HttpContext.Current.Cache以及HttpRuntime.Cache,HttpRuntime.Cache是應用程序級別的,而HttpContext.Current.Cache是針對當前WEB上下文定義的。HttpRuntime下的除了WEB中可以使用外,非WEB程序也可以使用。
1、HttpRuntime.Cache 相當於就是一個緩存具體實現類,這個類雖然被放在了 System.Web 命名空間下了。但是非 Web 應用也是可以拿來用的。
2、HttpContext.Cache 是對上述緩存類的封裝,由於封裝到了 HttpContext ,局限於只能在知道 HttpContext 下使用,即只能用於 Web 應用。
綜上所屬,在可以的條件,盡量用 HttpRuntime.Cache ,而不是用 HttpContext.Cache 。
一、有以下幾條緩存數據的規則
第一,數據可能會被頻繁的被使用,這種數據可以緩存。
第二,數據的訪問頻率非常高,或者一個數據的訪問頻率不高,但是它的生存周期很長,這樣的數據最好也緩存起來。
第三是一個常常被忽略的問題,有時候我們緩存了太多數據,通常在一台X86的機子上,如果你要緩存的數據超過800M的話,就會出現內存溢出的錯誤。所以說緩存是有限的。換名話說,你應該估計緩存集的大小,把緩存集的大小限制在10以內,否則它可能會出問題。在Asp.net中,如果緩存過大的話也會報內存溢出錯誤,特別是如果緩存大的DataSet對象的時候。
你應該認真分析你的程序。根據實際情況來看哪里該用,哪里不該用。如:cache用得過多也會增大服務器的壓力。整頁輸出緩存,又會影響數據的更新。 如果真的需要緩存很大量的數據,可以考慮靜態技術。
二、下面介紹HttpRuntime.Cache常用方法
C# 代碼
- <strong>using System;
- using System.Web;
- using System.Collections;
- public class CookiesHelper
- {
- /**//// <summary>
- /// 獲取數據緩存
- /// </summary>
- /// <param name="CacheKey">鍵</param>
- public static object GetCache(string CacheKey)
- {
- System.Web.Caching.Cache objCache = HttpRuntime.Cache;
- return objCache[CacheKey];
- }
- /**//// <summary>
- /// 設置數據緩存
- /// </summary>
- public static void SetCache(string CacheKey, object objObject)
- {
- System.Web.Caching.Cache objCache = HttpRuntime.Cache;
- objCache.Insert(CacheKey, objObject);
- }
- /**//// <summary>
- /// 設置數據緩存
- /// </summary>
- public static void SetCache(string CacheKey, object objObject, TimeSpan Timeout)
- {
- System.Web.Caching.Cache objCache = HttpRuntime.Cache;
- objCache.Insert(CacheKey, objObject, null, DateTime.MaxValue, Timeout, System.Web.Caching.CacheItemPriority.NotRemovable, null);
- }
- /**//// <summary>
- /// 設置數據緩存
- /// </summary>
- public static void SetCache(string CacheKey, object objObject, DateTime absoluteExpiration, TimeSpan slidingExpiration)
- {
- System.Web.Caching.Cache objCache = HttpRuntime.Cache;
- objCache.Insert(CacheKey, objObject, null, absoluteExpiration, slidingExpiration);
- }
- /**//// <summary>
- /// 移除指定數據緩存
- /// </summary>
- public static void RemoveAllCache(string CacheKey)
- {
- System.Web.Caching.Cache _cache = HttpRuntime.Cache;
- _cache.Remove(CacheKey);
- }
- /**//// <summary>
- /// 移除全部緩存
- /// </summary>
- public static void RemoveAllCache()
- {
- System.Web.Caching.Cache _cache = HttpRuntime.Cache;
- IDictionaryEnumerator CacheEnum = _cache.GetEnumerator();
- while (CacheEnum.MoveNext())
- ...{
- _cache.Remove(CacheEnum.Key.ToString());
- }
- }
- }
- </strong>