MVC版
1:Startup類
public void ConfigureServices(IServiceCollection services)
{
。。。忽略
services.AddMemoryCache();//啟用記憶體緩存
}
2:Controller調用
IMemoryCache _memoryCache;
public MyCacheController(IMemoryCache memoryCache)
{
_memoryCache = memoryCache;
}
public void MySize()
{
CancellationTokenSource tokenSource = new CancellationTokenSource();
var cacheOptions = new MemoryCacheEntryOptions()
{
//5s過期,被動過期,需要下一次被調用的時候,觸發‘RegisterPostEvictionCallback’
AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(5)
};
//過期觸發的回調方法,大家可以調試檢視key/value/reason/obj
cacheOptions.RegisterPostEvictionCallback((key, value, reason, obj) =>
{
Console.WriteLine(reason);
});
//添加主動過期回調
cacheOptions.AddExpirationToken(new CancellationChangeToken(tokenSource.Token));
_memoryCache.Set("key", "value", cacheOptions);
//2秒後主動過期,2秒後主動調用RegisterPostEvictionCallback方法
tokenSource.CancelAfter(1000 * 2);
}
控制台版本:
static void Main(string[] args)
{
//cache的最大限制是:100
MemoryCache memoryCache = new MemoryCache(new MemoryCacheOptions()
{
});
CancellationTokenSource tokenSource = new CancellationTokenSource();
var cacheOptions = new MemoryCacheEntryOptions()
{
AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(10) //10s過期
};
cacheOptions.RegisterPostEvictionCallback((key, value, reason, obj) =>
{
Console.WriteLine(reason);
});
cacheOptions.AddExpirationToken(new CancellationChangeToken(tokenSource.Token));
memoryCache.Set("key", "value", cacheOptions);
//System.Threading.Thread.Sleep(2000);
tokenSource.CancelAfter(1000 * 2);
Console.Read();
}