ASP.NET 快取資料添加的六種方法。(Insert 與add 的區別)

來源:互聯網
上載者:User

ASP.NET快取資料添加需求概述

ASP.NET使用緩衝機制,將需要大量伺服器資源來建立的Object Storage Service在記憶體中。緩衝這些類型的資源會大大改進應用程式的效能。緩衝是有Cache類實現的,可以通過對緩衝設定優先權CacheItemPriority枚舉值控制記憶體不夠時的“清理”優先順序。還可以為緩衝設定到期策略,以及為緩衝設定依賴項。

ASP.NET快取資料添加(將資料項目添加到緩衝中)

1、通過索引值對添加

  1. Cache["CacheItem"] = "Cached Item"; 

2、通過Insert 方法添加

Insert 方法向緩衝添加項,並且已經存在與現有項同名的項,則緩衝中的現有項將被替換。

  1. Cache.Insert("CacheItem", "Cached Item"); 

3、指定依賴項並添加(對添加到緩衝中的資料項目指定依賴項)

資料項目依賴一個字串數組對象的情況:

  1. string[] dependencies = { "Dependences" };  
  2. Cache.Insert("CacheItem",  
  3.     "Cached Item",  
  4.     new System.Web.Caching.CacheDependency(null, dependencies)); 

資料項目依賴一個XML檔案的情況:

  1. Cache.Insert("CacheItem", "Cached Item",  
  2.     new System.Web.Caching.CacheDependency(  
  3.     Server.MapPath("XMLFile.xml"))); 

資料項目依賴多個依賴項的情況:

  1. System.Web.Caching.CacheDependency dep1 =   
  2.     new System.Web.Caching.CacheDependency(Server.MapPath("XMLFile.xml"));  
  3. string[] keyDependencies2 = { "CacheItem1" };  
  4. System.Web.Caching.CacheDependency dep2 =   
  5.     new System.Web.Caching.CacheDependency(null, keyDependencies2);  
  6. System.Web.Caching.AggregateCacheDependency aggDep =   
  7.     new System.Web.Caching.AggregateCacheDependency();  
  8. aggDep.Add(dep1);  
  9. aggDep.Add(dep2);  
  10. Cache.Insert("CacheItem", "Cached Item", aggDep); 

4、設定到期策略並添加

添加一分鐘絕對到期時間到緩衝中:

  1. Cache.Insert("CacheItem", "Cached Item",  
  2.     null, DateTime.Now.AddMinutes(1d),   
  3.     System.Web.Caching.Cache.NoSlidingExpiration); 

添加10 分鐘彈性到期時間到緩衝中:

  1. Cache.Insert("CacheItem", "Cached Item",  
  2.     null, System.Web.Caching.Cache.NoAbsoluteExpiration,  
  3.     new TimeSpan(0, 10, 0)); 

5、設定優先權並添加

調用 Insert 方法,從 CacheItemPriority 枚舉中指定一個值。 

  1. Cache.Insert("CacheItem", "Cached Item",  
  2.     null, System.Web.Caching.Cache.NoAbsoluteExpiration,  
  3.     System.Web.Caching.Cache.NoSlidingExpiration,  
  4.     System.Web.Caching.CacheItemPriority.High, null); 

6、通過Add方法添加

Add 方法將返回您添加到緩衝中的對象。另外,如果使用 Add 方法,並且緩衝中已經存在與現有項同名的項,則該方法不會替換該項,並且不會引發異常。

  1. string CachedItem = (string)Cache.Add("CacheItem",  
  2.     "Cached Item", null,  
  3.     System.Web.Caching.Cache.NoAbsoluteExpiration,  
  4.     System.Web.Caching.Cache.NoSlidingExpiration,   
  5.     System.Web.Caching.CacheItemPriority.Default,  
  6.     null); 
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.