您的位置:首页 > 其它

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

2009-10-03 13:43 218 查看
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 ();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: