GetCache 的代码很简单: 有则取之,无则填之 ,“是否过期”是其有效性的唯一判断条件!接下来,作者就这个“是否过期”问题来进行一些探索,看看到底是怎么回事。
Ok ,还是先请大家看段代码:
代码 15 :过期无效之 Cache 篇! ** **
public class ** CacheManager **
{
private bool IsCacheExpired( string key)
{
bool bExpired = false ;
if ( ** HttpContext ** .Current != null )
{
// Web cache 自动支持 thread-safe ,无须锁定资源
if ( ** HttpContext ** .Current. ** Cache ** [key] == null )
bExpired = true ;
}
else
{
// Windows cache 是自己实现的,不确保 thread-safe ,必须锁定资源
lock (_htWinAppCache)
{
if (_htWinAppCache[key] == null )
bExpired = true ;
else
{
** WinAppCache ** cache = ( ** WinAppCache ** )
_htWinAppCache[key];
if (cache.IsExpired())
{
cache = null ;
_htWinAppCache[key] = null ;
bExpired = true ;
}
}
}
}
return bExpired;
}
}
各位,从上面的代码中,是否看出了一些端倪?
由于 Web Appliction Cache (通过 ** HttpContext ** .Current != null 判断是否 Web Application J )得到了 .NET Framework 的直接支持,所以判断“是否过期”非常方便,也不存在任何 thread-safe 问题 J 。但这个问题对于 Windows Application 来说就不太美妙了,既要自己实现 IsExpired ,又要担心多线程并发访问时的种种问题,真是吃力不讨好的苦差啊 L !上面代码中的“ _htWinAppCache ”(自定义 Cache ) 以及“ lock (_htWinAppCache) ”(确保 thread-safe ) 就是为了应付 Windows Application 而采取的两种非常手段!
可能有朋友会问了, Windows Application 也要考虑 Cache Management 问题吗?我的回答是:看情况而定!
对于普通的 Client Windows Application ,确实很少(请注意:不是没有)涉及这个话题,但对于 Server Application ,例如: ** Remoting Server ** , ** Windows Service ** ( WebServices 不在此列),都促使我们不得不面对“严峻的现实” L ( .NET Framework 怎么就没有提供 ** System.Windows.Caching ** 命名空间呢?害得我们不得不另起炉灶 L )!
上面的代码就是考虑到 Web Application 与 Windows Application 并存的情况下,我们该如何实现 Cache Management 支持!
当前版本中,作者实现 Windows Application 下的“是否过期”非常简单:就是看它被访问过几次!而这个次数,当然必须在配置信息中进行设定了(请参考本段最后的一个配置样例)!
Web Application 中的 Cache Management 自动化程度虽然很高,但也“逃不过”配置一关,而读取完配置信息后的处理工作就当仁不让地落到了 Parameter Classes 的肩上(请参考上面的 Cache Management 之“结构示意图”)!