内存缓存在.Net Framework 4中不起作用

时间:2018-10-20 17:27:40

标签: c# .net caching memorycache objectcache

我的项目建立在.Net Framework 4.0之上,我们使用ObjectCache中内置的MemoryCache,并在System.Runtime.Caching中实现。

它以前运行良好,但突然停止了将任何内容保存在缓存中。当我在缓存上调用Set方法时,它不会保存任何内容,并且Result View始终为空,说明为Enumeration yielded no results。我仔细检查了代码,发现没有发现问题。真的很简单,如下所示:

var policy = new CacheItemPolicy();
cache = new MemoryCache("MyCache");
cache.Set("item", "item value", policy);
var item = cache.Get("item");
cache.Remove("item"); //when removal is required

但是,在同一台计算机上针对.Net Framework 4的示例应用程序可以工作。我想知道是否还有其他人经历过类似的行为,我该如何解决这个问题的核心?有没有什么工具可以帮助您?

1 个答案:

答案 0 :(得分:0)

我终于找到了错误的原因。我正在处理具有容器控制的Cache实例的容器。在处理容器时,它也在处理我的缓存。而且它无法在已处理的缓存对象上设置值。它应该抛出异常,但没有,因此引起了整个混乱。以后的读者请注意。

var CachingPolicy = new CacheItemPolicy();
var Cache = new MemoryCache("YourCacheName");
container.RegisterInstance(CachingPolicy);
container.RegisterInstance(Cache);

container.Dispose(); //disposes cache as well. But calling methods on cache object won't throw exception.

//at this point, you should create the cache again, like
CachingPolicy = new CacheItemPolicy();
Cache = new MemoryCache("YourCacheName");
container.RegisterInstance(CachingPolicy);
container.RegisterInstance(Cache);

通过ILSpy进一步挖掘MemoryCache代码后,我们发现,如果放置了该对象,它不会设置任何内容。

if (IsDisposed)
{
    if (collection != null)
    {
        foreach (ChangeMonitor item in collection)
        {
            item?.Dispose();
        }
    }
}
else
{
    MemoryCacheKey memoryCacheKey = new MemoryCacheKey(key);
    MemoryCacheStore store = GetStore(memoryCacheKey);
    store.Set(memoryCacheKey, new MemoryCacheEntry(key, value, absExp, slidingExp, priority, collection, removedCallback, this));
}