【发布时间】:2017-11-06 09:01:50
【问题描述】:
我的应用程序中存在严重的内存泄漏。
这是在内存中加载很多东西的表单,它是一个带有 3 个FlowLayoutPanel 的表单。每个面板都有很多我创建的UserControl,它们只是一个带有标签的图片框。让我们调用表单ColorViewer:
每当我打开此表单时,它都会占用近 300-400 MB 的内存,而且似乎不会释放它。
当我第一次打开ColorViewer 时,它会将所有内容加载到内存中(接近 400mb),然后它就永远不会释放。之后,每次我打开ColorViewer 时,它都会正确处理。
这是我用来加载表单的代码,我猜内存泄漏是在加载 img 时。截至目前,我使用默认的Dispose():
//Loading of one of the three panel in the form,called 3 time when the form is opened:
colorsViewerPanel.AddColorRange(colours.ConvertAll(x => new ColorBox(x.path_img, x.id,true)));
//Function that loads my UserControl into the panel
public void AddColorRange(List<ColorBox> cBoxList)
{
flowLayoutPanel1.SuspendLayout();
foreach (var cBox in cBoxList)
flowLayoutPanel1.Controls.Add(cBox);
flowLayoutPanel1.ResumeLayout();
}
//This is the ColorBox usercontrol's class
public string pathImg{ get; set; }
public int id{ get; set; }
public bool selected{ get; set; }
//This is the constructor for the UserControl
public ColorBox(string pathImage,int idImage,bool sel = true)
{
InitializeComponent();
pathImg = pathImage;
id = idImage;
selected = sel;
//Load img
if (File.Exists(pathImg))
{
Image img;
using (var bmpTemp = new Bitmap(pathImg))
{
img = new Bitmap(pathImg);
}
panelColor.BackgroundImage = img;
panelColor.BackgroundImageLayout = ImageLayout.Stretch;
labelColor.Text = id;
}
}
这正常吗?
【问题讨论】:
-
内存不会自动释放回系统。它很难分配,因此 CLR 会尽可能长时间地保留它。如果您真的担心内存泄漏,可以使用一些工具来诊断(以及可以找到它们的搜索引擎)。
-
如果您不共享一行代码,我们如何为您提供帮助?
-
手动调用GC看是否释放?
-
您的声明“在那之后,每次我打开 ColorViewer 时它都会被正确处理”是没有意义的。要么正在处理,要么没有。除非你正在做一些相当奇怪的事情并且只是第一次。
-
@DonBoitnott 每次加载都是一样的,但是只有当我关闭程序或强制GC收集器通过dotMemory运行时才会清除第一次。我添加了发生内存泄漏的代码。
标签: c# winforms memory-leaks user-controls