C#中Cache的使用

來源:互聯網
上載者:User

標籤:blog   http   io   os   ar   使用   for   sp   檔案   

公用方法
Add 將指定項添加到 Cache 對象,該對象具有依賴項、到期和優先順序策略以及一個委託(可用於在從 Cache 移除插入項時通知應用程式)。 
Equals(從 Object 繼承) 已重載。確定兩個 Object 執行個體是否相等。 
Get 從 Cache 對象檢索指定項。 
GetEnumerator 檢索用於逐一查看包含在緩衝中的鍵設定及其值的字典枚舉數。 
GetHashCode(從 Object 繼承) 用作特定類型的雜湊函數,適合在雜湊演算法和資料結構(如雜湊表)中使用。 
GetType(從 Object 繼承) 擷取當前執行個體的 Type。 
Insert 已重載。向 Cache 對象插入項。使用此方法的某一版本改寫具有相同 key 參數的現有 Cache 項。 
Remove 從應用程式的 Cache 對象移除指定項。 
ToString(從 Object 繼承) 返回表示當前 Object 的 String。


public object Add(
   string key,
   object value,
   CacheDependency dependencies,
   DateTime absoluteExpiration,
   TimeSpan slidingExpiration,
   CacheItemPriority priority,
   CacheItemRemovedCallback onRemoveCallback
);

參數
key 
用於引用該項的緩衝鍵。 
value 
要添加到緩衝的項。 
dependencies 
該項的檔案依賴項或緩衝鍵依賴項。當任何依賴項更改時,該對象即無效,並從緩衝中移除。如果沒有依賴項,則此參數包含Null 參考(Visual Basic 中為 Nothing)。 
absoluteExpiration 
所添加對象將到期並被從緩衝中移除的時間。 
slidingExpiration 
最後一次訪問所添加對象時和該對象到期時之間的時間間隔。如果該值等效於 20 分鐘,則對象在最後一次被訪問 20 分鐘之後將到期並從緩衝中移除。 
priority 
對象的相對成本,由 CacheItemPriority 枚舉表示。緩衝在退出對象時使用該值;具有較低成本的對象在具有較高成本的對象之前被從緩衝移除。 
onRemoveCallback 
在從緩衝中移除對象時所調用的委託(如果提供)。當從緩衝中刪除應用程式的對象時,可使用它來通知應用程式。
樣本
public void AddItemToCache(Object sender, EventArgs e) {
    itemRemoved = false;

    onRemove = new CacheItemRemovedCallback(this.RemovedCallback);

    if (Cache["Key1"] == null)
      Cache.Add("Key1", "Value 1", null, DateTime.Now.AddSeconds(60), TimeSpan.Zero, CacheItemPriority.High, onRemove);
}

 

 

將資料添加到緩衝中

1。通過指定其鍵和值將項添加到緩衝中 
Cache["txt"] = "a";

2.通過使用 Insert(重載Insert方法)方法將項添加到緩衝中

Cache.Insert("txt", "a");

下列代碼顯示如何設定相對到期策略。它插入一個項,該項自上次訪問後 10 分鐘到期。注意 DateTime.MaxValue 的使用,它表示此項沒有絕對到期策略。

DateTime absoluteExpiration=DateTime.MaxValue;
TimeSpan slidingExpiration=TimeSpan.FromMinutes(10);
Cache.Insert("txt", "a",null,
absoluteExpiration,slidingExpiration,
System.Web.Caching.CacheItemPriority.High,null);

3.使用 Add 方法將項添加到緩衝中 
Add 方法與 Insert 方法具有相同的簽名,但它返回表示您所添加項的對象

DateTime absoluteExpiration=DateTime.MaxValue;
TimeSpan slidingExpiration=TimeSpan.FromMinutes(10);
Object  Ojb=(string)Cache.Add("txt","a",null,
absoluteExpiration ,slidingExpiration ,
System.Web.Caching.CacheItemPriority.High,null);
string str=(string)Ojb ;
Response.Write(str);

結果顯示是"a"

Add 方法使用上沒有Insert 方法靈活,使用Add 方法時必須提供7個參數,Insert 方法重載4次,我們可以根據需要選擇適當重載方法


從緩衝中取得資料

方式1:
string str=(string)Cache.Get("txt");
Response.Write(str);

方式2:
string str1=(string)Cache["txt1"];
Response.Write(str1);

查看Cache中所有資料

System.Text.StringBuilder sb=new System.Text.StringBuilder("",100);
foreach(DictionaryEntry Caches  in Cache)
{
sb.Append("key=").Append(Caches.Key.ToString()).Append("
") ;
sb.Append("value=").Append(Caches.Value.ToString()).Append("
");
}
Response.Write(sb.ToString());

查看Cache中的項數

int Count=Cache.Count;
Response.Write(Count.ToString());


將資料從緩衝中刪除

Cache.Remove("txt");

使Cache具有檔案依賴項或鍵依賴項的對象

我們在一頁面建立1個按鈕,查看CACHE是否存在
在表單啟動時我們建立CACHE,名稱="txt2",數值=資料集ds
該CACHE與myfile.xml相關聯,當myfile.xml檔案變化時,txt2CACHE就被自動刪除

private void Page_Load(object sender, System.EventArgs e)
  {
   if( !IsPostBack  )
   {
   string FilePath=MapPath("myfile.xml");
   SqlConnection con=new SqlConnection("Uid=sa;database=pubs;");
   SqlDataAdapter da =new SqlDataAdapter("select * from authors",con);
   DataSet ds=new DataSet();
   da.Fill(ds);
   System.Web.Caching.CacheDependency CacheDependencyXmlFile=new System.Web.Caching.CacheDependency(FilePath);
   Cache.Insert("txt2",ds ,CacheDependencyXmlFile);
   }
  }


為了監視pubs資料庫authors表的變化
我們可以在pubs資料庫authors表建立觸發器
一旦authors表中發生增加,刪除,修改資料時,觸發器會自動修改檔案myfile.xml
一旦myfile.xml檔案變化,txt2CACHE就被系統自動刪除

CREATE TRIGGER tr_authors
ON authors
FOR INSERT, UPDATE ,delete
AS 
declare @cmd nvarchar(4000)
select @cmd=‘bcp "select convert(nvarchar(30),Getdate(),13)" queryout D:/cache/WebCache/myfile.xml -c -Sglc2403 -Usa -P‘
exec master..xp_cmdshell @cmd
GO


private void QueryButton_Click(object sender, System.EventArgs e)
{
if ( Cache["txt2"]!=null)
{
 Response.Write("exists");
}
else
{
 Response.Write("not exists");
}
}

首先我們點按鈕,顯示Cache["txt2"]存在
現在我們去表authors中任意修改一資料,再點按鈕,顯示Cache["txt2"]不存在拉


以上我們是把CACHE是和一個檔案相關聯,我們還可以把CACHE和檔案組關聯,建立依賴
以下我們把CACHE和2個檔案(myfile.xml,myfile1.xml)關聯,一旦檔案組中其中任意一檔案變化,Cache會把"txt2"項的資料從CACHE中刪除

string[] FilePath=new String[]{MapPath("myfile.xml"),MapPath("myfile1.xml")};
System.Web.Caching.CacheDependency CacheDependencyXmlFile=new                     System.Web.Caching.CacheDependency(FilePath);
string CacheVaule="a";
Cache.Insert("txt2", CacheVaule ,CacheDependencyXmlFile);

 


緩衝依賴可以是檔案,還可以是其他對象的鍵
下面的代碼說明緩衝Cache["txt2"]既依賴檔案myfile.xml,又依賴緩衝中的Cache["txt"],只要這2者任意一樣改變,緩衝Cache["txt2"]就會清除

Cache["txt"] = "b";
string[] FilePath=new String[]{ MapPath("myfile.xml")};
string[] dependencyKey=new String[]{"txt"};
SqlConnection con=new SqlConnection("Uid=sa;database=pubs;");
SqlDataAdapter da =new SqlDataAdapter("select * from authors",con);
DataSet ds=new DataSet();
da.Fill(ds);
System.Web.Caching.CacheDependency CacheDependencyXmlFile=
          new System.Web.Caching.CacheDependency(FilePath,dependencyKey);
Cache.Insert("txt2",ds ,CacheDependencyXmlFile);


緩衝絕對到期

緩衝Cache["txt3"] 在1小時後自動到期
DateTime absoluteExpiration =DateTime.Now.AddHours(1);
Cache.Insert("txt3","aa",null,absoluteExpiration,System.Web.Caching.Cache.NoSlidingExpiration);

緩衝相對(滑動)到期

注意:如果建立的彈性到期時間小於零或大於一年,則將引發異常
緩衝Cache["txt4"] 在最後一次被訪問後1小時自動到期
TimeSpan slidingExpiration=TimeSpan.FromHours(1);
Cache.Insert("txt4","4",null,System.Web.Caching.Cache.NoAbsoluteExpiration,slidingExpiration);


快取項目的優先等級

當承載 ASP.NET 應用程式的 Web 服務器缺少記憶體時,Cache 將有選擇地清除項來釋放系統記憶體。當向緩衝添加項時,可以為其分配與緩衝中儲存的其他項相比較的相對優先順序。在伺服器處理大量請求時,分配了較高優先順序值的項被從緩衝刪除的可能性較小,而分配了較低優先順序值的項則更有可能被刪除。
由CacheItemPriority 枚舉表示,預設為 Normal。

緩衝Cache["txt5"]優先等級設為最高等級,在伺服器釋放系統記憶體時,該快取項目最不可能被刪除。
Cache.Insert("txt5","5",null,
System.Web.Caching.Cache.NoAbsoluteExpiration,
System.Web.Caching.Cache.NoSlidingExpiration,
System.Web.Caching.CacheItemPriority.High,null);

快取項目時通知應用程式的回調方法

ASP.NET 提供 CacheItemRemovedCallback 委託。它定義編寫事件處理常式時使用的簽名,當從緩衝中刪除項時,該事件處理常式將進行響應。


static System.Web.Caching.CacheItemRemovedReason reason;
System.Web.Caching.CacheItemRemovedCallback onRemove = null;

public void RemovedCallback(String k, Object v, System.Web.Caching.CacheItemRemovedReason r)
{
 itemRemoved = true;
 reason = r;
}

onRemove = new System.Web.Caching.CacheItemRemovedCallback (this.RemovedCallback);
Cache.Insert("txt",ds,null,
System.Web.Caching.Cache.NoAbsoluteExpiration,
System.Web.Caching.Cache.NoSlidingExpiration,
System.Web.Caching.CacheItemPriority.Default,onRemove);

 

由於任何原因從Cache中移除時,將調用 RemovedCallback 方法

出處:http://blog.csdn.net/thecityofsky/article/details/4770231

C#中Cache的使用

相關文章

聯繫我們

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