2015-11-04 65 views
2

誰能告訴我如何最好地處理內存流?以前,我有這個,一切都工作得很好:正確處理內存流(WPF圖像轉換)

MemoryStream strmImg = new MemoryStream(profileImage.Image); 
BitmapImage myBitmapImage = new BitmapImage(); 
myBitmapImage.BeginInit(); 
myBitmapImage.StreamSource = strmImg; 
myBitmapImage.DecodePixelWidth = 200; 
myBitmapImage.DecodePixelWidth = 250; 
myBitmapImage.EndInit(); 
this.DemographicInformation.EmployeeProfileImage = myBitmapImage; 

後來我才意識到,我要去有內存泄漏的MemoryStream的實現IDisposable,應予以處置後,我用它害得我這個執行:

using(MemoryStream strmImg = new MemoryStream(profileImage.Image)) 
{ 
    BitmapImage myBitmapImage = new BitmapImage(); 
    myBitmapImage.BeginInit(); 
    myBitmapImage.StreamSource = strmImg; 
    myBitmapImage.DecodePixelWidth = 200; 
    myBitmapImage.DecodePixelWidth = 250; 
    myBitmapImage.EndInit(); 
    this.DemographicInformation.EmployeeProfileImage = myBitmapImage; 
} 

問題是在這行代碼:

myBitmapImage.StreamSource = strmImg; 

我的假設是,這是引用的內存位置和處置顯然將清除locatio ñ和它在過去,因爲它從來沒有妥善處置

我的問題是,如何使用MemoryStream和使用後妥善處理,同時仍然保留我需要的轉換數據(圖像)?

謝謝

ROKA

+1

注意,這是處置的MemoryStream(只是因爲它是一次性的)很好的做法,但如果你不這樣做實際上並沒有泄漏。特別是,Dispose實際上並不釋放內存;只有當GC收集MemoryStream時纔會發生這種情況。由於BitmapImage保留對MemoryStream的引用,因此在收集BitmapImage之前不能收集它。 –

回答

5

您需要添加此行:

myBitmapImage.CacheOption = BitmapCacheOption.OnLoad; 

其中在加載時整個圖像緩存到內存中。沒有這一行,CacheOption屬性的默認值是OnDemand,它保留對流的訪問權限,直到需要映像爲止。所以,你的代碼應該是:

using(MemoryStream strmImg = new MemoryStream(profileImage.Image)) 
{ 
    BitmapImage myBitmapImage = new BitmapImage(); 
    myBitmapImage.BeginInit(); 
    myBitmapImage.CacheOption = BitmapCacheOption.OnLoad; 
    myBitmapImage.StreamSource = strmImg; 
    myBitmapImage.DecodePixelWidth = 200; 
    myBitmapImage.DecodePixelWidth = 250; 
    myBitmapImage.EndInit(); 
    this.DemographicInformation.EmployeeProfileImage = myBitmapImage; 
} 
+0

工程很棒。謝謝! – Roka