2009-10-20 105 views
1

我在其中一個項目中遇到過這樣的代碼,它有一個靜態函數用於從文件返回MemoryStream,然後將其存儲在Cache中。現在,同一個類有一個構造函數,它允許將MemoryStream存儲在一個私有變量中,並稍後使用它。所以它看起來像這樣:在緩存中存儲MemoryStream

private MemoryStream memoryStream; 

public CountryLookup(MemoryStream ms) 
{ 
    memoryStream = ms; 
} 

public static MemoryStream FileToMemory(string filePath) 
{ 
    MemoryStream memoryStream = new MemoryStream(); 
    ReadFileToMemoryStream(filePath, memoryStream); 

    return memoryStream; 
} 

用法:

Context.Cache.Insert("test", 
       CountryLookup.FileToMemory(
        ConfigurationSettings.AppSettings["test"]), 
       new CacheDependency(someFileName) 
       ); 

然後:

CountryLookup cl = new CountryLookup(
       ((MemoryStream)Context.Cache.Get("test")) 
       ); 

所以我想知道誰應該處置的MemoryStream是什麼時候?理想情況下,CountryLookup應該實現IDisposable。

我應該關心它嗎?

回答

7

這有點難看 - 特別是,MemoryStream是有狀態的,因爲它具有「當前位置」的概念。

爲什麼不直接存儲一個字節數組呢?您可以輕鬆地構建多個MemoryStream,它們在需要時包裝相同的字節數組,並且不需要擔心有狀態。

MemoryStreams不需要通常需要處置,但我個人傾向於擺脫他們的習慣。如果您對它們執行異步操作或在遠程處理中使用它們,我認爲處理在這一點上有所作爲。字節數組更簡單:)

+2

+1,用於在緩存中存儲byte []數組 - MemoryStream的實例成員不保證是線程安全的。 – 2009-10-20 06:26:37