【发布时间】:2017-05-21 05:03:49
【问题描述】:
我正在尝试编写一个类来处理 .net 核心类库中的内存缓存。如果我不使用核心,那么我可以写
using System.Runtime.Caching;
using System.Collections.Concurrent;
namespace n{
public class MyCache
{
readonly MemoryCache _cache;
readonly Func<CacheItemPolicy> _cachePolicy;
static readonly ConcurrentDictionary<string, object> _theLock = new ConcurrentDictionary<string, object>();
public MyCache(){
_cache = MemoryCache.Default;
_cachePolicy = () => new CacheItemPolicy
{
SlidingExpiration = TimeSpan.FromMinutes(15),
RemovedCallback = x =>
{
object o;
_theLock.TryRemove(x.CacheItem.Key, out o);
}
};
}
public void Save(string idstring, object value){
lock (_locks.GetOrAdd(idstring, _ => new object()))
{
_cache.Add(idstring, value, _cachePolicy.Invoke());
}
....
}
}
}
在 .Net 核心中我找不到 System.Runtime.Cache。在阅读了.net coreIn Memory Cache之后,我添加了参考Microsoft.Extensions.Caching.Memory (1.1.0) 并尝试了
using System.Collections.Concurrent;
using Microsoft.Extensions.Caching.Memory;
namespace n
{
public class MyCache
{
readonly MemoryCache _cache;
readonly Func<CacheItemPolicy> _cachePolicy;
static readonly ConcurrentDictionary<string, object> _theLock = new ConcurrentDictionary<string, object>();
public MyCache(IMemoryCache memoryCache){
_cache = memoryCache;// ?? **MemoryCache**;
}
public void Save(string idstring, object value){
lock (_locks.GetOrAdd(idstring, _ => new object()))
{
_cache.Set(idstring, value,
new MemoryCacheEntryOptions()
.SetAbsoluteExpiration(TimeSpan.FromMinutes(15))
.RegisterPostEvictionCallback(
(key, value, reason, substate) =>
{
object o;
_locks.TryRemove(key.ToString(), out o);
}
));
}
....
}
}
}
希望 save 方法中的代码没问题,尽管目前我的大多数 mycache 测试都失败了。谁能指出什么是错的? 主要问题是关于构造函数我应该如何设置缓存而不是 MemoryCache.Default
_cache = memoryCache ?? MemoryCache.Default;
【问题讨论】:
标签: c# caching .net-core memorycache