如何使用Microsoft企业库中的CacheManager缓存实现IDisposable接口的对象?
当一个对象到期时,从不为该对象调用Dispose(),我也不能覆盖Remove(...)。
答案 0 :(得分:2)
我并不完全清楚调用Dispose应该是缓存的责任;仅仅因为从缓存中删除了一个项目并不意味着它没有在其他地方被引用。
此外,如果一个对象实现了IDisposable模式,那么Finalizer应该调用Dispose(如果尚未调用Dispose)。
但是,Enterprise Library确实为您提供了一个钩子,允许您执行您认为必要的任何操作。接口是ICacheItemRefreshAction接口。从缓存中删除项目时,将在单独的线程上调用ICacheItemRefreshAction.Refresh方法。
当一个项目被添加到缓存时,可以指定ICacheItemRefreshAction。
其用法示例:
[Serializable]
public class DisposeRefreshAction : ICacheItemRefreshAction
{
public void Refresh(string key, object expiredValue, CacheItemRemovedReason removalReason)
{
// Item has been removed from cache. Perform desired actions here, based on
// the removal reason (for example, refresh the cache with the item).
if (expiredValue != null && expiredValue is IDisposable)
{
((IDisposable)expiredValue).Dispose();
}
}
}
public class MyClass : IDisposable
{
public void Dispose()
{
Console.WriteLine("Dispose!");
}
}
var cache = EnterpriseLibraryContainer.Current.GetInstance<CacheManager>("Cache Manager");
cache.Add("myKey", new MyClass(), CacheItemPriority.Normal,
new DisposeRefreshAction(), new SlidingTime(TimeSpan.FromSeconds(2)));