2011-04-06 129 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

相關問題