我需要在處理所有使用的對象後減少c#WPF中的內存泄漏。但是我不能完全通過使用下面的代碼片段來減少內存消耗。在C#中的內存泄漏WPF
這裏是我的代碼:
string str;
Uri uri;
private void Button_Click(object sender, RoutedEventArgs e) // "Load" Button
{
if(img.Source!=null)
Unload();
str = "F://Photos//Parthi//IMG_20141128_172826244.jpg"; // File Size: 0.643 MB
uri = new Uri(str);
img.Source = new BitmapImage(uri);
}
private void Button_Click_1(object sender, RoutedEventArgs e) //"Unload Button"
{
Unload();
}
private void Unload()
{
Bitmap bmp = GetBitmap(img.Source as BitmapSource);
bmp.Dispose();
bmp = null;
img.Source = null;
str = string.Empty;
uri = null;
}
private Bitmap GetBitmap(BitmapSource source)
{
Bitmap bmp = new Bitmap(source.PixelWidth, source.PixelHeight, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
BitmapData data = bmp.LockBits(new System.Drawing.Rectangle(System.Drawing.Point.Empty, bmp.Size), ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
source.CopyPixels(Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride);
bmp.UnlockBits(data);
data = null;
source = null;
return bmp;
}
運行示例,而在任務管理器檢查它,下面的內存消耗閱讀已經產生,
之前「Load」按鈕點擊後:10.0 MB
後 「Load」 按鈕被點擊:47.8 MB
後 「卸載」 按鈕被點擊:26.0 MB
卸載後,我需要將內存緊密地減少到10.0 MB。所以請幫助我解決這個問題。
在此先感謝。
在'Unload'函數末尾調用'GC.Collect()' – dotctor 2014-12-03 06:12:01
'Bitmap'繼承自'Image',它實現了'IDisposable' ...爲什麼不只是利用它並使用'using'呢?順便說一句,爲什麼你有這樣嚴格的要求,你不能讓WPF和.NET爲你處理內存?我可能是錯的,但是我覺得如果你想要這樣的微觀管理水平,C或C++可能是更好的選擇。 – 2014-12-03 06:23:06
你在閱讀什麼記憶指標? – leppie 2014-12-03 07:25:18