我已经按照http://www.codeproject.com/Articles/167282/NET-4-0-MemoryCache-with-SqlChangeMonitor上的示例实现了一个内存缓存
我有一个问题,根本没有添加缓存。
我的代码:
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Runtime.Caching;
namespace ClassLibrary{
public partial class TRANSLATION {
public static string GetTranslationString(int id)
{
string trans = TRANSLATION.cached.Where(x => x.id == id).Select(x => x.Value).FirstOrDefault();
if (trans == null)
{
return "";
}
else {
return trans;
}
}
public static List<TRANSLATION> cached()
{
List<TRANSLATION> lstTRANSLATION;
if (MemoryCache.Default["TRANSLATION"] == null)
{
CacheItemPolicy policy = new CacheItemPolicy();
SqlDependency.Start(cacher.sqlConn());
using (SqlConnection conn = new SqlConnection(cacher.sqlConn()))
{
using (SqlCommand command = new SqlCommand("SELECT [ID],[Value] FROM [TRANSLATION]", conn))
{
command.Notification = null;
SqlDependency dep = new SqlDependency();
dep.AddCommandDependency(command);
conn.Open();
SqlDataReader sqlReader = command.ExecuteReader();
lstTRANSLATION = new List<TRANSLATION>();
while (sqlReader.Read())
{
TRANSLATION trans = new TRANSLATION();
trans.ID = sqlReader.GetInt32(0);
trans.Value = sqlReader.GetString(1);
lstTRANSLATION.Add(trans);
}
SqlChangeMonitor monitor = new SqlChangeMonitor(dep);
policy.ChangeMonitors.Add(monitor);
}
}
MemoryCache.Default.Add("TRANSLATION", lstTRANSLATION, policy);
}
else
{
lstTRANSLATION = (List<TRANSLATION>)MemoryCache.Default.Get("TRANSLATION");
}
return lstTRANSLATION;
}
}
}
当我单步执行代码时,它没有找到缓存,即使是 .add() 之后的行,我也找不到缓存。
当我添加以下代码时:
MemoryCache.Default.Add("test", "test", DateTime.Now.AddMinutes(5));
我可以在缓存中找到这个键。
我究竟做错了什么?