.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コアを読んだ後メモリキャッシュ内、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);
}
));
}
....
}
}
}
現時点ではほとんどのmycacheテストが失敗していますが、saveメソッド内のコードは問題ないと思います。何が間違っているのか指摘していただけませんか?主な質問はコンストラクタについてです。代わりにキャッシュを設定するにはどうすればいいでしょうか?メモリキャッシュ.デフォルト
_cache = memoryCache ?? MemoryCache.Default;
ベストアンサー1
コンストラクターは次のとおりです。
using Microsoft.Extensions.Caching.Memory;
. . .
MemoryCache myCache = new MemoryCache(new MemoryCacheOptions());