2012-12-27 32 views
0

我有一個用C#編寫的函數,它在檢查並插入緩存後返回業務實體(make)的集合。
數據緩存從函數返回空值的機會

public static Collection<CProductMakesProps> GetCachedSmartPhoneMake(HttpContext context) 
    { 
     var allMake = context.Cache["SmartPhoneMake"] as Collection<CProductMakesProps>; 
     if (allMake == null) 
     { 
      context.Cache.Insert("SmartPhoneMake", new CModelRestrictionLogic().GetTopMakes(), null, 
           DateTime.Now.AddHours(Int32.Parse(ConfigurationManager.AppSettings["MakeCacheTime"])), 
           Cache.NoSlidingExpiration); 

      allMake = context.Cache["SmartPhoneMake"] as Collection<CProductMakesProps>; 
     } 
     return allMake; 
    } 

我在其他頁面使用它,如下所示

var lobjprodMakeCol = CBrandCache.GetCachedSmartPhoneMake(Context); 
//CBrandCache is the class which contain the method 

是否有可能,我得到的lobjprodMakeCol

由於空值。


編輯

new CModelRestrictionLogic().GetTopMakes()是從數據庫中提取記錄的功能。
它將返回0或更多的收集天氣。

回答

1

有少數的可能性時,你的函數可以返回null - 他們是

  1. GetTopMakes功能它自身返回null
  2. 緩存過期時間是零(MakeCacheTime CONFI g條目具有零值)
  3. 鑄造as Collection<CProductMakesProps>失敗 - 如果GetTopMakes 返回一些不同的類型可能。

我寧願以下版本,它不會在所有的上述情況下

var allMake = context.Cache["SmartPhoneMake"] as Collection<CProductMakesProps>; 
if (allMake == null) 
{ 
    allMake = new CModelRestrictionLogic().GetTopMakes(); 
    context.Cache.Insert("SmartPhoneMake", allMake, 
     null, DateTime.UtcNow.AddHours(Int32.Parse(
     ConfigurationManager.AppSettings["MakeCacheTime"])), Cache.NoSlidingExpiration); 
} 
return allMake; 

返回null另請注意,使用的DateTime.UtcNow將避免任何意外,如日光節約等

+0

感謝您的建議和答覆。但我想知道你和@slugster方法有什麼區別? –

+0

@krshekhar,正如我所說的,即使緩存過期時間爲零(表示不需要緩存),上面的代碼也不會返回null。值得注意的是,它消除了緩存未命中情況下不必要的緩存查找,但是在方案中這並不重要!此外,你可以進一步重新考慮上面的代碼,從靜態構造函數中讀取緩存過期時間,但是再次... – VinayC

1

是的,如果演員as Collection<CProductMakesProps>失敗,則空值將被分配給allMake,所以這很大程度上取決於您從new CModelRestrictionLogic().GetTopMakes()返回的內容。

基於這樣的假設,大部分緩存和/或字典集合將允許你檢查特定關鍵的presense,我建議寫這一個稍微精簡的方式:

public static Collection<CProductMakesProps> GetCachedSmartPhoneMake(HttpContext context) 
{ 
    if (!context.Cache.ContainsKey("SmartPhoneMake") || context.Cache["SmartPhoneMake"] == null) 
    { 
     context.Cache.Insert("SmartPhoneMake" 
          , new CModelRestrictionLogic().GetTopMakes() 
          , null 
          , DateTime.Now.AddHours(Int32.Parse(ConfigurationManager.AppSettings["MakeCacheTime"])) 
          , Cache.NoSlidingExpiration); 
    } 

    return context.Cache["SmartPhoneMake"] as Collection<CProductMakesProps>; 
} 
+0

如果轉換爲'Collection '失敗,那麼null將被分配給allMake ** true **,但在此之後,空檢查將爲該上下文分配值。緩存是否正確? –

+1

@krshekhar在你的代碼中你有兩個不同的'cast'實例作爲集合',這將會(默默地)失敗並且返回null,如果它被應用的類型不能被這種方式轉換。你的問題是*是否有可能在lobjprodMakeCol?*中得到空值,答案是*是,可以用代碼*的方式。 – slugster