Caching For .Net Framework Applications(一)

ASP.NET缓存机制详解
本文介绍了ASP.NET中缓存机制的基本概念及多种缓存策略,包括基于文件变化、其他缓存项、相对时间和绝对时间的过期策略,并展示了如何在缓存过期时执行特定函数。

  Cache在System.Web.Cacheing命名空间中定义,它是一种key/value的object。类似Session Objcet和application Object,ViewState Object都可以当作Cache来使用。但是Cache在.net 中还有其它很多特性,例如依赖属性和自动过期的一些策略等。我们先用一些简单的示例来了解Cache的概念。

  (1)最简单的Cache的使用:

Cache["Time"= DateTime.Now.ToString();
lblCacheTime.Text 
= Cache["Time"].ToString()
Cache.Remove(
"Time");

 

  (2):基于硬盘上的文件变化的一种Cache的过期策略

CacheDependency dependucy = new CacheDependency(“customdatasource.xml");
                Cache.Insert("Time", strDateTime, dependucy); 

  当CustomDataSource.xml中的内容发生变化时Cache中Time为Key的缓存就会被移除。当然我们还基于一批文件。CacheDependency这个类中提供很多构造函数,有兴趣的朋友可以去查一下MSDN。

  (3):基于其它缓存的Key的一种Cache过期策略

  

ExpandedBlockStart.gif代码
// Create a cache entry.
Cache["key1"= "Value 1";

// Make key2 dependent on key1.
String[] dependencyKey = new String[1];
dependencyKey[
0= "key1";
CacheDependency dependency 
= new CacheDependency(null, dependencyKey);

Cache.Insert(
"key2""Value 2", dependency);

 

  (4):基于相对时间和绝对时间的一种Cache过期策略

 

ExpandedBlockStart.gif代码
/// Absolute expiration
Cache.Insert("CachedItem", item, null, DateTime.Now.AddSeconds(5), 
    Cache.NoSlidingExpiration);
/// Sliding expiration
Cache.Insert("CachedItem", item, null, Cache.NoAbsoluteExpiration, 
    TimeSpan.FromSeconds(
5));
  

  (5)当Cache过期时被执行的时候,还可以执行一些函数,来做一些工作。

 

ExpandedBlockStart.gif代码
CacheItemRemovedCallback onRemove = new 
CacheItemRemovedCallback(
this.RemovedCallback);
Cache.Insert(
"CachedItem"
    item, 
    
null,
    Cache.NoAbsoluteExpiration,
    Cache.NoSlidingExpiration,
    CacheItemPriority.Default,
    onRemove);

// Implement the function to handle the expiration of the cache.
public void RemovedCallback(string key, object value, CacheItemRemovedReason r)
{
   
// Test whether the item is expired, and reinsert it into the cache.
   if (r == CacheItemRemovedReason.Expired)
   {
      
// Reinsert it into the cache again.
      CacheItemRemovedCallback onRemove = null;
      onRemove 
= new CacheItemRemovedCallback(this.RemovedCallback);
      Cache.Insert(key,  
                       value,
                       
null,
                       Cache.NoAbsoluteExpiration,
                       Cache.NoSlidingExpiration,
                       CacheItemPriority.Default,
                       onRemove);
   }
}
    本文只是记录和总结了一下看到的信息,接下的文章将介绍Cache的一些实际的应用。  

转载于:https://www.cnblogs.com/BlueWoods/archive/2010/11/22/1884739.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值