private xxx _info;
public static object lockInfo;
private static DateTime beginTime;
public xxx Info
{
get
{
TimeSpan timespan = DateTime.Now - beginTime;
if (_info == null || timespan.Days >= 30)
{
lock (lockInfo)
{
if (_info == null || timespan.Days >= 30)
{
beginTime = DateTime.Now;
_info = DataContext.info.where(p => p.id == id).FirstOrDefault();
}
}
}
return _info;
}
}
也就是我把他做成一个方法函数,然后把这个函数方法标识成缓存,不知怎么写了...我用的是MVC,但MVC的缓存只可以对ActionResult才有效。
asp.net提供缓存的,自己写函数实现,简单一点的
if( HttpContext.Cache["temp"]==null)
{
HttpContext.Cache["temp"]=DataContext.info.where(p => p.id == id).FirstOrDefault();
}
return HttpContext.Cache["temp"] as List<Object>();
所以用.net的MemoryCache;http://msdn.microsoft.com/zh-cn/library/system.runtime.caching.memorycache.aspx
看列子~ 你自己把他封装得更好一点
其实就是把https://efcache.codeplex.com/里面的那段代码复制到你的项目中即可,不用其它任何修改。
搜索的话找“ef second level cache”或“ef二级缓存”
//利用Cache.Add()方法加入缓存
//将数据项目加入缓存
protected void btnAddCache_Click(object sender, EventArgs e)
{
//利用Cache.Add()方法将数据加入缓存
Cache.Add("Name", txtUserName.Text, null, System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Default, null);
Cache.Add("Photo", txtTel.Text, null, System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Default, null);
Cache.Add("Position", txtJob.Text, null, System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Default, null);
txtMsg.Text = "缓存加入成功!";
}
//显示缓存数据
protected void btnDisplayCache_Click(object sender, EventArgs e)
{
IDictionaryEnumerator CacheIDE = Cache.GetEnumerator();//显示缓存数据
int i = 0;
string info = null;
info += "缓存项目数据(Key / Value):" + "<br>";
while (CacheIDE.MoveNext())//循环输出缓存项目
{
info += i.ToString() + ". ";
info += CacheIDE.Key.ToString() + " : ";
info += CacheIDE.Value.ToString() + "<br>";
i++;
}//CodeGo.net/
if (Cache["Name"] == null)//判断缓存是否有数据项目
{
txtMsg.Text = "缓存内容为Null值!";
}
else
{
txtMsg.Text = info;
}
}