关于缓存C#

今天把网站中缓存的部分看了下,之前一直很神秘,不知boss怎么写的,认为是很牛B的东东,看过后也不过如此了。 

   缓存所在的命名空间为System.Web.Caching

   管理缓存的类为Cache 对缓存的增删都由他来实现,Cache属于字典类,需要缓存对象的键值。Cache是sealed定义过的类,不能被继承,同时他还实现了IEnumerable接口

   Cache类主要的方法:

   

public Object Add (

     string key,

     Object value,

     CacheDependency dependencies,

     DateTime absoluteExpiration,

     TimeSpan slidingExpiration,

     CacheItemPriority priority,

     CacheItemRemovedCallback onRemoveCallback

)

在使用Add方法时,以上7个参数是必需的,其代表意义如下:

— 参数“key”代表缓存数据项的键值,必须是唯一的。

— 参数“value”代表缓存数据的内容,可以是任意类型。

— 参数“dependencies”表示缓存的依赖项,也就是此项的更改意味着缓存内容已经过期。如果没有依赖项,可将此值设置为NULL。

— 参数“absoluteExpiration”是日期型数据,表示缓存过期的时间,.NET 2.0提供的缓存在过期后是可以使用的,能使用多长时间,就看这个参数的设置。

— 参数“slidingExpiration”的类型表示一段时间间隔,表示缓存参数将在多长时间以后被删除,此参数与absoluteExpiration参数相关联。

— 参数“priority”表示撤销缓存的优先值,此参数的值取自枚举变量“CacheItemPriority”,优先级低的数据项将先被删除。此参数主要用在缓存退出对象时。

— 参数“onRemoveCallback”表示缓存删除数据对象时调用的事件,一般用做通知程序。

 

  

ArrayList myarray = new ArrayList();         //创建数组数据

        myarray.Add("1.学习园地");

        myarray.Add("2.交流论坛");

        myarray.Add("3.帮助");

        //添加缓存中

        Cache.Add("Category", myarray, null, DateTime.Now.AddSeconds(60), TimeSpan.Zero, CacheItemPriority.Normal, null);

        myarray[1] = "2.交流园地";                     //修改数组数据  

        Cache.Insert("Category", myarray);           //使用Insert方法修改缓存数据

        string tmpStr = "这是一个临时数据";

        Cache["tmpdata"] = tmpStr;

        //使用Get方法获取缓存数据

        Response.Write(Cache.Get("tmpdata").ToString()+"<br/>");/

        Cache["tmpdata"] = "这是一个临时字符串";         //重新为缓存赋值的技巧

        Response.Write(Cache.Get("tmpdata").ToString() + "<br/>");

        //使用GetType方法判断缓存数据的类型

        if (Cache["Category"].GetType().Name == "ArrayList")

            Response.Write("类型是数组");

        //使用GetEnumerator方法遍历缓存中的数据

        IDictionaryEnumerator mycache = Cache.GetEnumerator();

        while (mycache.MoveNext())

            Response.Write(mycache.Value + "<br/>");

        Cache.Remove("tmpdata");//使用Remove方法移除缓存的临时数据

 

Cache简单的使用就这些 更详细的在http://www.cnblogs.com/anorthwolf/archive/2009/12/07/1618665.html

posted on 2013-05-24 23:47  staben  阅读(195)  评论(0编辑  收藏  举报

导航