C# 知識點總結(二)

來源:互聯網
上載者:User

Cache用法之頁面聲明

<%@ outputCache
Duration="#ofseconds"
Location="Any|Client|Downstream|Server|None"
VaryByControl="ControlName"
VaryByCustom="browser|customstring"
VaryByHeader="headers"
VaryByParam="Parametername" %>

Cache用法之代碼控制
HttpCachePolicy類是專門用來控制項Cache的,可以用Response.Cahce來訪問這個類的執行個體

Response.Cache.SetExpires(DateTime.Now.AddSeceonds(10));
Response.Cache.SetCacheability(HttpCacheablility.Public);
Response.Cache.SetValidUnitlExpires(true);

-----------------------以上都是快取頁面面的,下面是快取資料的----------------------------
Cache類的生存周期等於應用程式的生命週期
三種用法
1:存:Cache["key"] = MyData;取:
MyData = Cache["key"];
if(MyData != null)
    use(MyData);
此法存入Cache的資料生命週期等於應用程式生命週期,不支援清除、到期、依賴性等功能。

2:存:
Cache.Insert(
string key,
object value,
CacheDependency dependencies,//依賴,設定緩衝有效依賴性,比如設定和一個檔案相關,檔案一變,就失效
DateTime absoluteExpireation,  //設定固定的到期時間
TimeSpan slidingExpiration, //設定最後一次訪問後多長時間到期
CachePriority priority, //設定記憶體不足,緩衝自動清除時,緩衝的重要性,可不可以清除
CacheItemRemovedCallback onRemoveCallback // 設定在清除時引發的事件
)
Example:

Cache.Insert("Mydata",MyData,new Caching.CacheDependency(Server.MapPah("Mydata.XML")));//設定有效性和一個檔案有關
Cache.Insert("Mydata",myData,null,DateTime.Now.AddDays(1),Cache.NoSlidingExpiratin);//兩種到期時間設了其中一種,另一種要設為0,用NoAbsolute(Sliding)Expiration枚舉
Cache.Insert("MyData",myData,null,Cache.NoAbsoluteExpiration,TimeSpan.FromMinutes(10));//不能過一年不能小於0
Cache.Insert("MyData",myData,null,Cache.NoAbsoluteExpiration,TimeSpan.FromMinutes(10),
  Caching.CacheItemPriority.NotRemovable,null);
 // AboveNormal|BelowNormal|Default|High|Low|Normal|NotRemovable

public void RemovedCallback(string key,object value,CacheItemRemovedReason reason)
{
    if(reason == CacheItemRemovedReason.DependencyChanged)
        Response.Write("檔案變了,快去看看");
}
Cache.Insert("Mydata",MyData,new Caching.CacheDependency(Server.MapPah("Mydata.XML"),
  DateTime.Now.AddDays(1),Cache.NoSlidingExpiration,CacheItemPriority.High,
  new CacheItemRemovedCallback(this.RemovedCallback));

清除就可以用Cache.Remove("key");方法

3:
Cache.Add方法,用法和Insert差不多,區別在於Add碰到該key原來有賦過值會失敗,Insert則不會,而會替換原有值;Add會返回被快取資料項,Insert不會

文章來自: 鴻石網際(http://www.hungstone.cn/)

相關文章

聯繫我們

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