电脑爱好者,提供IT资讯信息及各类编程知识文章介绍,欢迎大家来本站学习电脑知识。 最近更新 | 联系我们 RSS订阅本站最新文章
电脑爱好者
站内搜索: 
当前位置:首页>> C#>>C#中Cache的使用 add-get读取和写入缓存代码:

C#中Cache的使用 add-get读取和写入缓存代码

来源:网络 | 2013-4-29 | (有7523人读过)

公共方法 
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  
该项的文件依赖项或缓存键依赖项。当任何依赖项更改时,该对象即无效,并从缓存中移除。如果没有依赖项,则此参数包含空引用(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://www.knowsky.com/539463.html
C#热门文章排行
网站赞助商
购买此位置

 

关于我们 | 网站地图 | 文档一览 | 友情链接| 联系我们

Copyright © 2003-2024 电脑爱好者 版权所有 备案号:鲁ICP备09059398号