C#内存在Bitmap中泄漏

我的应用程序在这行中出现内存泄漏。如果我看一下任务管理器,每次触发此过程时,RAM内存增加+ – 300 MB ..

Bitmap bmp1 = new Bitmap(2480, 3508); panel1.DrawToBitmap(bmp1, new Rectangle(0, 0, 2480, 3508)); pictureBox2.Image = bmp1; 

有人可以帮我解决他的泄漏吗? 如果我使用:

 bmp1.Dispose(); 

我在这行的“Program.cs”中得到一个例外: Application.Run(new Form1()); 在此之后,应用程序停止运行…

屏幕应用: 在此处输入图像描述

更新:本身没有内存泄漏,您只需等待垃圾收集器释放资源。

如果你确实希望collect垃圾收集器,你可以这样做:

 System.GC.Collect(); System.GC.WaitForPendingFinalizers(); 

为什么需要处理位图? 如果您的PictureBox正在使用它,那么您需要位图。 如果你要更改它,也许你应该将旧位图切换为新位图并处理旧位图:

 Bitmap bmp1 = new Bitmap(2480, 3508); panel1.DrawToBitmap(bmp1, new Rectangle(0, 0, 2480, 3508)); Image img = pictureBox1.Image; pictureBox1.Image = bmp1; if (img != null) img.Dispose(); // the first time it'll be null 

我假设你应该只处理你不再需要的图像。 您仍然需要创建bmp1 ,您只需将其设置为pictureBox2.Image字段的内容即可。 尝试这些方面的东西:

 Bitmap bmp1 = new Bitmap(2480, 3508); panel1.DrawToBitmap(bmp1, new Rectangle(0, 0, 2480, 3508)); Bitmap bmp2 = (Bitmap)pictureBox2.Image; pictureBox2.Image = bmp1; bmp2.Dispose(); 

免责声明:我对C#没有经验,所以我可能错了……

  Bitmap copy_Screen() { try { var bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb); var gfxScreenshot = Graphics.FromImage(bmpScreenshot); try { gfxScreenshot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy); } catch (Exception) { } return bmpScreenshot; } catch (Exception) { } return new Bitmap(10, 10, PixelFormat.Format32bppArgb); } private void button5_Click(object sender, EventArgs e) { //Start Stop timer if (timer1.Enabled == false) { timer1.Enabled = true; } else { timer1.Enabled = false; } } private void timer1_Tick(object sender, EventArgs e) { //memory leak solve System.GC.Collect(); System.GC.WaitForPendingFinalizers(); Bitmap BM = copy_Screen(); if (pictureBox1.Image != null) { pictureBox1.Image.Dispose(); } pictureBox1.Image = BM; }