位图中的 C# 内存泄漏

标签 c# image 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()); 在此之后,应用程序停止运行......

屏幕应用: enter image description here

最佳答案

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

如果您确实想让垃圾收集器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(); // this may be null on the first iteration

关于位图中的 C# 内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14957896/

相关文章:

c++ - winapi:从 HDC 到 HBITMAP

c# - 在 C# 中读取 PPM 图像

c# - 在 C# 中的 ArrayList 中检索对象中的参数?

c# - 使用 DirectorySearcher 从大型 AD 组获取 SamAccountName

c# - 如何修复 "Unable to remove directory ' 共享'。访问路径 'obj\Debug\netcoreapp2.1\Razor\Pages\Shared' 被拒绝”

c++ - 使用 C++ 从多个网络摄像头捕获图片

c# - 如何从表中逐 block 获取数据?

html - 为什么在我的 <a> 元素下会出现 4px 的额外填充?

java - 如何在 Java 小程序中获取像素的颜色来生成 map ?

android - 包含位图的动态壁纸 Canvas 会闪烁