我试图缓存从SQL服务获取的数据,我尝试使用System.Runtime.Caching中的内存缓存类,但似乎每当我退出应用程序时缓存都被清空。
所以我的问题是,有没有办法缓存我的数据,所以即使我的应用程序重新启动我也能得到它?
使用Biztalk的服务,因此应用程序会在需要时启动,但SQL轮询时间过长。
以下是代码即时测试:
const string KEY = "key";
static void Main(string[] args)
{
MemoryCache cache = MemoryCache.Default;
Cache(cache);
Get(cache);
Console.Read();
}
private static void Get(MemoryCache cache)
{
string result = cache.Get(KEY) as string;
Console.WriteLine(result);
}
private static void Cache(MemoryCache cache)
{
CacheItemPolicy policy = new CacheItemPolicy();
policy.AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(10);
bool res = cache.Add(KEY, "This was Cached", policy);
if (res)
Console.WriteLine("Added Succesfully");
else
Console.WriteLine("Adding Failed");
}
答案 0 :(得分:0)
所以我的问题是,有没有办法缓存我的数据,所以即使我的应用程序重新启动我也能得到它?
是。如果使用CacheItemPriority.NotRemovable
,即使应用程序重新启动,缓存仍然存在。
ObjectCache cache = System.Runtime.Caching.MemoryCache.Default;
CacheItemPolicy policy = new CacheItemPolicy
{
Priority = CacheItemPriority.NotRemovable,
AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(10);
};
cache.Add(item, policy);
MSDN注意:向优先级为NotRemovable的缓存添加条目可能会使缓存中的条目永远无法删除。缓存实现应该只为缓存条目设置NotRemovable优先级,如果它们提供了从缓存中逐出这些条目并管理缓存条目数的方法。