ASP.NET緩存數據添加方法一覽
ASP.NET緩存數據添加需求概述
ASP.NET使用緩存機制,將需要大量服務器資源來創建的對象存儲在內存中。緩存這些類型的資源會大大改進應用程序的性能。緩存是有Cache類實現的,可以通過對緩存設置優先級CacheItemPriority枚舉值控制內存不夠時的“清理”優先順序。還可以為緩存設置過期策略,以及為緩存設置依賴項。
ASP.NET緩存數據添加(將數據項添加到緩存中)
1、通過鍵值對添加
- Cache["CacheItem"] = "Cached Item";
2、通過Insert 方法添加
Insert 方法向緩存添加項,并且已經存在與現有項同名的項,則緩存中的現有項將被替換。
- Cache.Insert("CacheItem", "Cached Item");
3、指定依賴項并添加(對添加到緩沖中的數據項指定依賴項)
數據項依賴一個字符串數組對象的情況:
- string[] dependencies = { "Dependences" };
- Cache.Insert("CacheItem",
- "Cached Item",
- new System.Web.Caching.CacheDependency(null, dependencies));
數據項依賴一個XML文件的情況:
- Cache.Insert("CacheItem", "Cached Item",
- new System.Web.Caching.CacheDependency(
- Server.MapPath("XMLFile.xml")));
數據項依賴多個依賴項的情況:
- System.Web.Caching.CacheDependency dep1 =
- new System.Web.Caching.CacheDependency(Server.MapPath("XMLFile.xml"));
- string[] keyDependencies2 = { "CacheItem1" };
- System.Web.Caching.CacheDependency dep2 =
- new System.Web.Caching.CacheDependency(null, keyDependencies2);
- System.Web.Caching.AggregateCacheDependency aggDep =
- new System.Web.Caching.AggregateCacheDependency();
- aggDep.Add(dep1);
- aggDep.Add(dep2);
- Cache.Insert("CacheItem", "Cached Item", aggDep);
4、設置過期策略并添加
添加一分鐘絕對過期時間到緩存中:
- Cache.Insert("CacheItem", "Cached Item",
- null, DateTime.Now.AddMinutes(1d),
- System.Web.Caching.Cache.NoSlidingExpiration);
添加10 分鐘彈性過期時間到緩存中:
- Cache.Insert("CacheItem", "Cached Item",
- null, System.Web.Caching.Cache.NoAbsoluteExpiration,
- new TimeSpan(0, 10, 0));
5、設置優先級并添加
調用 Insert 方法,從 CacheItemPriority 枚舉中指定一個值。
- Cache.Insert("CacheItem", "Cached Item",
- null, System.Web.Caching.Cache.NoAbsoluteExpiration,
- System.Web.Caching.Cache.NoSlidingExpiration,
- System.Web.Caching.CacheItemPriority.High, null);
6、通過Add方法添加
Add 方法將返回您添加到緩存中的對象。另外,如果使用 Add 方法,并且緩存中已經存在與現有項同名的項,則該方法不會替換該項,并且不會引發異常。
- string CachedItem = (string)Cache.Add("CacheItem",
- "Cached Item", null,
- System.Web.Caching.Cache.NoAbsoluteExpiration,
- System.Web.Caching.Cache.NoSlidingExpiration,
- System.Web.Caching.CacheItemPriority.Default,
- null);
以上就介紹了ASP.NET緩存數據添加的六種方法。本文來自菩提屋:《緩存應用程序數據(一)》
【編輯推薦】