提高应用程序的性能----全局应用程序缓存

1-所有的地方都提供 了对全局Cache的访问.全局应用程序缓寸,具有绝对过期/可调过期/缓寸依赖(文件/目录/数据库依赖),缓寸删除回调.
Context.Cache.Insert ("Stocks"(key), ds(cache obj), null(缓寸依赖),
    Cache.NoAbsoluteExpiration(绝对过期), TimeSpan.FromHours (1)(可调过期),
    CacheItemPriority.AboveNormal(缓寸对象优先级别), null(删除回调));
Context.Cache.Add ("Stocks", ds, null,
    Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration,
    CacheItemPriority.Default, null);
例子:
<%@ Import Namespace="System.Data" %>

<script language="C#" runat="server">
  static Cache _cache;
  static string _path;

  void Application_Start ()
  {
      _cache = Context.Cache;
      _path = Context.Server.MapPath ("Stocks.xml");

      DataSet ds = new DataSet ();
      ds.ReadXml (_path);

      _cache.Insert ("Stocks", ds, new CacheDependency (_path),
          Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration,
          CacheItemPriority.Default,
          new CacheItemRemovedCallback (RefreshDataSet));
  }

  static void RefreshDataSet (String key, Object item,
      CacheItemRemovedReason reason)
  {
      DataSet ds = new DataSet ();
      ds.ReadXml (_path);

      _cache.Insert ("Stocks", ds, new CacheDependency (_path),
          Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration,
          CacheItemPriority.Default,
          new CacheItemRemovedCallback (RefreshDataSet));
  }
</script>

 

2/线程安全:

The application cache doesn’t have Lock and UnLock methods as application state does. But that doesn’t mean locking isn’t necessary; it means you have to come up with your own mechanism for doing it. System.Threading.ReaderWriterLock is the perfect tool for the job. Assuming rwlock is an instance of ReaderWriterLock, here’s how you’d lock the application cache during an update:

rwlock.AcquireWriterLock (Timeout.Infinite);
try {
    Cache["ItemsSold"] = (int) Cache["ItemsSold"] + 1;
    Cache["ItemsLeft"] = (int) Cache["ItemsLeft"] - 1;
}
finally {
    rwlock.ReleaseWriterLock ();
}

And here’s how you’d read “ItemsSold” and “ItemsLeft” values from the cache:

rwlock.AcquireReaderLock (Timeout.Infinite);
try {
    int sold = (int) Cache["ItemsSold"];
    int left = (int) Cache["ItemsLeft"];
}
finally {
    rwlock.ReleaseReaderLock ();
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值