[英]C# bitmaps causes memory leak
我有一個簡單的應用程序,可以渲染圖像並將其打印出來。 為了簡化設計,我使用了自定義Control
。
現在,我有一個簡單的控件,大小為1800 x 2400(是的,非常大):
public class PhotoControl : UserControl
{
public PhotoControl()
{
InitializeComponent();
}
}
還有一個擴展類,它使用它來生成圖像:
public static class PhotoProcessor
{
private static readonly PhotoControl PhotoForm = new PhotoControl(); // Single instance
public static Image GenerateImage(this Photo photo)
{
PhotoForm.SetPhoto(photo); // Apply a photo
Image result;
using (Bitmap b = new Bitmap(PhotoForm.Width, PhotoForm.Height))
{
Rectangle r = new Rectangle(0, 0, b.Width, b.Height);
PhotoForm.DrawToBitmap(b, r); // Draw control to bitmap
using (MemoryStream ms = new MemoryStream())
{
b.Save(ms, ImageFormat.Png); // Save bitmap as PNG
result = Image.FromStream(ms);
}
}
// GC.Collect();
// GC.WaitForPendingFinalizers();
return result; // return
}
現在,我嘗試使用此生成30張照片:
myPhoto.GenerateImage().Save(@"Output1.png", ImageFormat.Png);
myPhoto.GenerateImage().Save(@"Output2.png", ImageFormat.Png);
我不存儲參考,我只是保存圖像,並期望GC保存到文件后會收集這些圖像。
這將需要大約2 GB的內存,並最終引發異常:
System.Drawing.dll中發生類型為'System.OutOfMemoryException'的未處理異常
附加信息:內存不足。
如果我看一下Visual Studio診斷工具,它看起來像:
讓我們做個快照,看看堆的內容,我們將看到有很多MemoryStream
:
是什么導致MemoryStream
產生內存泄漏? 據我所知, using()
生成Dispose()
調用,應該對此進行處理。
PS如果我刪除注釋並調用GC.Collect(); GC.WaitForPendingFinalizers();
GC.Collect(); GC.WaitForPendingFinalizers();
,則所需的內存減少了2-3倍,但仍會增長-大約200張圖片仍會殺死應用程序。
將圖像保存更改為以下內容:
Image img;
img = myPhoto.GenerateImage();
img.Save(@"Output1.png", ImageFormat.Png);
img.Dispose();
img = myPhoto.GenerateImage();
img.Save(@"Output2.png", ImageFormat.Png);
img.Dispose();
將產生與使用GC.Collect();
相同的結果GC.Collect();
。 它還將占用較少的內存,但不能消除內存泄漏。
Image
實現IDisposable
,因此必須手動處理。 您當前正在從GenerateImage
返回一個Image
,但是在保存后不進行處理。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.