2
如何使用Microsoft Enterprise Library中的CacheManager缓存实现IDisposable接口的对象?EntLib CacheManager和IDisposable对象
当一个对象到期时,从不为该对象调用Dispose(),也无法重写Remove(...)。
如何使用Microsoft Enterprise Library中的CacheManager缓存实现IDisposable接口的对象?EntLib CacheManager和IDisposable对象
当一个对象到期时,从不为该对象调用Dispose(),也无法重写Remove(...)。
我不完全清楚它应该是调用Dispose的缓存的责任;只是因为一个项目从缓存中删除并不意味着它没有被其他地方引用。另外,如果一个对象实现了IDisposable模式,那么Finalizer应该调用Dispose(如果Dispose尚未被调用)。
但是,企业库确实会为您提供一个挂钩,以便您执行任何您认为必要的操作。该接口是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)));
你能调用Dispose在缓存中的对象的析构函数?或者你不拥有这些类的代码? – rene 2011-12-27 14:05:48
我确实有这些类的代码,并会给它一个镜头,虽然它感觉哈克不知何故。 – 2011-12-27 14:12:25
完全同意,我希望别人提出一个更好的解决方案 – rene 2011-12-27 14:20:41