我創建了一個圖像使用此功能後:一個BitmapImage的配置問題的公司被凍結
private BitmapImage LoadImage(byte[] imageData)
{
if (imageData == null || imageData.Length == 0) return null;
var image = new BitmapImage();
using (var mem = new MemoryStream(imageData))
{
mem.Position = 0;
image.BeginInit();
image.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
image.CacheOption = BitmapCacheOption.OnLoad;
image.UriSource = null;
image.StreamSource = mem;
image.EndInit();
}
image.Freeze();
return image;
}
當我試圖處置它:
myImage.StreamSource.Close();
myImage.StreamSource.Dispose();
// Throws an exception since its frozen to read only
//myImage.StreamSource = null;
GC.Collect();
它不會被垃圾收集器收集。可能因爲我無法將其設置爲null
。
我該如何處置這個BitmapImage
因此它不會在內存中活得更久?
我可以用此代碼確認字節數組沒有被釋放,但仍有一個引用的地方。你可以通過給它添加一個'WeakReference'並檢查'IsAlive'屬性來測試它。我在發佈模式下執行此操作時沒有附加任何調試器。 – Stuart
增加了一些測試代碼。在這種情況下,我不確定爲什麼'IsAlive'對你來說是'真的'。如果我在同一個函數和Debug模式下調用了GC,它會返回'true',但是如果它處於相同的函數和釋放模式下,它仍然是'false'。也許你可以分享你使用的確切代碼? – RandomEngy
@Stuart當跟蹤傳入內存流的字節數組時,我也會得到相同的結果。 – RandomEngy