2013-12-17 71 views
-2

我有一個高速緩存方法如下: -更改緩存改變列表對象C#

編輯

// Cache Methods 
    public void dbcTvShowsList(ref List<TvShow> listTvShows, ref Int16 err) 
    { 
     // Check to see if tv shows are already in cache 
     if (HttpRuntime.Cache["TvShows"] != null) 
     { 
      listTvShows = (List<TvShow>)HttpRuntime.Cache["TvShows"]; 

      // Make sure we have data in the list 
      if (listTvShows.Count == 0) 
      { 
       // No data in the list. Read it from the database 
       // Now cache the data 
      } 
      else 
      { 
       // Now cache the data 
       HttpRuntime.Cache.Insert("TvShows", listTvShows, null, DateTime.Now.AddMinutes(3), System.Web.Caching.Cache.NoSlidingExpiration); 
      } 
     } 
     else 
     { 
      // Data no longer in cache. Read it from the database 

      // If we got data, cache it 
      if (err == 0) 
      { 
       HttpRuntime.Cache.Insert("TvShows", listTvShows, null, DateTime.Now.AddMinutes(3), System.Web.Caching.Cache.NoSlidingExpiration); 
      } 
     } 
    } 

現在在我的班級我讀緩存的數據,然後出不來了一些更改, 。但是這影響了我的緩存數據,如下所示: -

new iNGRID_Data.TvShows.DataMethods().dbcTvShowsList(ref _TvShows, ref err); 
TvShow TvShowAll = new TvShow(); 
TvShowAll.ShowId = 0; 
TvShowAll.ShowName = "All Programming"; 
_TvShows.Add(TvShowAll); 

這會修改全局緩存並將所有編程添加到它。

你能告訴我爲什麼會發生這種情況嗎?

問候 阿布舍克

+0

您只有對列表的引用。這不是一個副本。 – scheien

回答

1

因爲你是在傳遞通過ref關鍵字列表。您不是在使用本地/新增的清單副本,而是參考了您通過的清單。不確定爲什麼ref在這裏需要誠實。

另外,你的邏輯和評論似乎有點過:

// Make sure we have data in the list 
if (listTvShows.Count == 0) 
{ 
    // No data in the list. Read it from the database 
} 
else 
{ 
    // Now cache the data 
    HttpRuntime.Cache.Insert("TvShows", listTvShows, null, DateTime.Now.AddMinutes(3), System.Web.Caching.Cache.NoSlidingExpiration); 
} 

您檢查是否有數據,如果不從數據庫中獲取,但沒有將其插入到緩存中(大概)。

然後在你的其他你聲明你插入數據到緩存中,爲什麼?如果代碼已經存在,那麼這段代碼實質上就是將數據插入到緩存中。當然你想要的是相反的?例如。

if(listTvShows.Count == 0) 
{ 
    //fetch from db 
    //insert into cache 
} 

//no need for an else, do whatever you need with the data 
+0

如果密鑰不存在,listTvShows也可以爲空。 – scheien

+0

我也試過。這修改了全局緩存的數據。答案似乎與我問的問題不同。 – vishal

+0

@scheien是的 - 我們總是空檢查我們的緩存層。 – DGibbs