C#内存在Bitmap中泄漏

Fer*_*ans 5 c# image bitmap

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

Bitmap bmp1 = new Bitmap(2480, 3508);
panel1.DrawToBitmap(bmp1, new Rectangle(0, 0, 2480, 3508));
pictureBox2.Image = bmp1;
Run Code Online (Sandbox Code Playgroud)

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

bmp1.Dispose();
Run Code Online (Sandbox Code Playgroud)

我在此行的"Program.cs"中遇到异常:Application.Run(new Form1()); 在此之后,应用程序停止运行...

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

Ada*_*ean 12

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

如果你确实想制作垃圾收集器collect,你可以这样做:

System.GC.Collect();
System.GC.WaitForPendingFinalizers();
Run Code Online (Sandbox Code Playgroud)

为什么需要处理位图?如果您的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
Run Code Online (Sandbox Code Playgroud)