我想永久缓存某些值,并想确保当我访问它们时它们就在那里。
目前我使用以下代码:
ObjectCache objectCache = MemoryCache.Default;
CacheItemPolicy policy = new CacheItemPolicy() { AbsoluteExpiration = ObjectCache.InfiniteAbsoluteExpiration };
objectCache.Set(new CacheItem("anykey", anyobject), policy);
在 MSDN 文档中,有关 ObjectCache.InfiniteAbsoluteExpiration 设置的内容如下:
However, a cache entry with this setting can be evicted from the cache for other reasons that are determined by a particular cache implementation, such as a change-monitor event eviction caused by memory pressure.
这是否意味着,如果我的 Windows 服务因 OutOfMemoryException 崩溃,所有缓存值都将被清除?
最佳答案
简短的回答是:是的,即使您使用 InfiniteAbsoluteExpiration,也可以逐出或清除缓存值。
如果您的程序无法处理丢失的缓存值(它可能应该这样做),那么您需要处理删除项目以逐出的情况,无论 OutOfMemoryExceptions 是什么。 MemoryCache(作为 ObjectCache 的一部分)有一个 UpdateCallback 委托(delegate),可以这样设置:
private void PopulateCache(Widget value)
{
var policy = new CacheItemPolicy();
policy.UpdateCallback = CacheUpdate;
_cache.Set(GetCacheItemKey(value), value, policy);
}
private void CacheUpdate(CacheEntryUpdateArguments args)
{
// if expired or evicted, put it back in!
if (args.RemovedReason == CacheEntryRemovedReason.Expired || args.RemovedReason == CacheEntryRemovedReason.Evicted)
{
_cache.Set(args.Key, _cache[args.Key], CacheItemPolicy);
}
// if removed or ChangeMonitorChanged, do nothing
}
欲了解更多信息,请查看:https://msdn.microsoft.com/en-us/library/dd988702(v=vs.110).aspx
作为最佳实践,典型的模式是,当您从缓存中检索值时,如果该项目已过期/被逐出,您应该从数据存储中获取该项目并重新填充缓存。
关于c# - 即使使用 InfiniteAbsoluteExpiration,值也可以从 ObjectCache 中逐出吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31453492/