2011-04-06 131 views
1

我试图使用Microsoft企业库的缓存应用程序块。我已经使用MS企业库V5.0在asp.net中使用企业库缓存应用程序块mvc2

以下是我在家庭控制器的索引方法中所做的示例代码。

 Person p = new Person(10, "person1"); 
     ICacheManager cacheMgr = CacheFactory.GetCacheManager("myCache"); 
     ViewData["Message"] = "Welcome to ASP.NET MVC!"; 

     if (Session["currsession"] != null) 
     { 
      if (!cacheMgr.Contains(p.pid.ToString())) 
      { 
       Response.Write("item is not in cache"); 
       return View(p); 
      } 
      else 
      { 
       Response.Write("item is still in cache"); 
       return View(p); 
      } 
     } 
     else 
     { 
      Session["currsession"] = 1; 
      cacheMgr.Add(p.pid.ToString(), p, CacheItemPriority.High, null, new SlidingTime(TimeSpan.FromSeconds(10))); 
      return View(cacheMgr.GetData(p.pid.ToString())); 
     } 

我在模型中使用的人类只有一个具有2个公共属性的构造函数。没有使用任何特殊功能。

现在,这是正确的程序使用企业库缓存块的缓存。如果没有,我还能如何以有效的方式编码这段代码。

此外,我得到的响应只有在20秒后延迟item is not in cache。在代码的实现中是否存在任何错误,或者是否存在详细的缓存背后的理论。

请提出这种用法的最佳做法。

回答

0

既然你指定的10秒的滑动过期,这意味着你会得到item is not in cache如果你等待重新加载页面之间超过10秒。

负荷首次开庭=>没有消息
刷新=>在缓存
刷新=>在缓存
等待10秒钟
刷新=>不在缓存

这就是你”再见?


老答案:

企业缓存应用程序块可能的方式比你更需要。我最喜欢的缓存是FubuMVC的缓存(只包含FubuCore.dll)。通过使用具有“缺少元素”委托的ConcurrentDictionary,可以获得非常类似的实现。这里有一个例子:http://social.msdn.microsoft.com/Forums/en/parallelextensions/thread/37bbc361-6851-43db-9e90-80cc7e6ac15f

FubuMVC缓存例如:

public class PersonCache 
{ 
    private Cache _Cache = new Cache(); 

    public PersonCache() 
    { 
     _Cache.OnMissing = key => MyDatabase.People.GetById(key); 
    } 

    public Person GetById(int id) 
    { 
     return _Cache[id]; 
    } 
} 
+0

感谢您的建议。请注意,我的查询是如何维护同一会话中多个页面刷新之间的缓存。为此,我使用了一个会话变量。这是正确的方法。请分析我的代码并给我回复。 – Saravanan 2011-04-06 07:13:25

+0

对不起,我想我从来没有读完这个问题。这是凌晨2点这里,所以我没有真正的重点。 – Ryan 2011-04-06 07:23:07

相关问题