在我做的项目中是内存泄漏.我重写了所有修复一些的功能,但还剩下一个:
该程序有一个面板对象数组,每当我放入一个新的面板时,它会增长.当它达到400个面板时,它会删除最旧的面板以释放一些内存.
我不明白的是以下内容:
tempPanels = new Panel[panels.Length];
Array.Copy(panels, 1, tempPanels, 0, panels.Length - 1);//delete the oldest history log (the first of the array)
panels = null; //empty object array
panels = new Panel[tempPanels.Length + 1]; //set new length
tempPanels.CopyTo(panels, 0);//restore panels
Run Code Online (Sandbox Code Playgroud)
当我使用上面的代码时,内存使用量仍在不断增加...有人可以解释为什么我必须首先处理面板才能将面板设置为null吗?
tempPanels = new Panel[panels.Length];
Array.Copy(panels, 1, tempPanels, 0, panels.Length - 1);//delete the oldest history log (the first of the array)
panels[0].Dispose();
panels = null; //empty object array
panels = new Panel[tempPanels.Length + 1]; //set new length
tempPanels.CopyTo(panels, 0);//restore panels
Run Code Online (Sandbox Code Playgroud)
提前致谢!
EDIT @ Steve B:
该程序创建了一个新面板:panel currentPanel;
当有一个新面板时,我声明了currentPanel:currentPanel = new Panel();
之后我调用了这个函数:setCurrentPanelConfiguration:
public void setCurrentPanel()
{
currentPanel.Name = "panel" + panels.Length;
currentPanel.Size = new System.Drawing.Size(485, 75);
currentPanel.BackColor = Color.Transparent;
}
Run Code Online (Sandbox Code Playgroud)
要修复滚动错误,我使用Panel HistoryPanel放置currentPanel:
HistoryPanel.Controls.Add(currentPanel);
Run Code Online (Sandbox Code Playgroud)
然后我添加所有控件:用户名,当前时间和头像.
为了保存面板,我在创建空间后将其添加到阵列面板,如上所示:
panels[panels.Length-1] = currentPanel;
我使用数组,因为历史记录显示最新的数组.每次我必须将所有面板80px向下移动时这样做.
Gra*_*mas 11
因为设置某些内容null并不处理它,它只是取消引用它 - 垃圾收集器不监视您的分配以检查您的null引用,它是在它需要时(其他所有条件相同)或明确告知这样做时.
总之,因为null和内存管理是不同的事情.