【发布时间】:2013-09-26 01:17:01
【问题描述】:
从 MemoryCache 实例中删除大量项目的推荐方法是什么?
根据围绕this question 的讨论,似乎首选方法是为整个应用程序使用单个缓存,并使用 namespaces 作为键以允许缓存多种逻辑类型的项目同一个实例。
但是,使用单个缓存实例会导致大量项目从缓存中过期(删除)。特别是在某种逻辑类型的所有项目都必须过期的情况下。
目前我找到的唯一解决方案是基于answer to this question,但从性能的角度来看,它确实不是很好,因为您必须枚举缓存中的所有键,并测试命名空间,这可能相当耗时!
目前我想出的唯一解决方法是为缓存中的所有对象创建一个带有版本号的瘦包装器,并且每当访问一个对象时,如果缓存版本与当前版本。所以每当我需要清除某种类型的所有项目时,我都会提高当前版本号,使所有缓存的项目无效。
上面的解决方法似乎很可靠。但我不禁想知道是否没有更直接的方法来完成同样的任务?
这是我当前的实现:
private class MemCacheWrapper<TItemType>
where TItemType : class
{
private int _version;
private Guid _guid;
private System.Runtime.Caching.ObjectCache _cache;
private class ThinWrapper
{
public ThinWrapper(TItemType item, int version)
{
Item = item;
Version = version;
}
public TItemType Item { get; set; }
public int Version { get; set; }
}
public MemCacheWrapper()
{
_cache = System.Runtime.Caching.MemoryCache.Default;
_version = 0;
_guid = Guid.NewGuid();
}
public TItemType Get(int index)
{
string key = string.Format("{0}_{1}", _guid, index);
var lvi = _cache.Get(key) as ThinWrapper;
if (lvi == null || lvi.Version != _version)
{
return null;
}
return lvi.Item;
}
public void Put(int index, TItemType item)
{
string key = string.Format("{0}_{1}", _guid, index);
var cip = new System.Runtime.Caching.CacheItemPolicy();
cip.SlidingExpiration.Add(TimeSpan.FromSeconds(30));
_cache.Set(key, new ThinWrapper(item, _version), cip);
}
public void Clear()
{
_version++;
}
}
【问题讨论】:
标签: .net caching memorycache