在我制作的项目中出现了内存泄露问题。我重新编写了所有函数来修复一些问题,但仍有一个问题没有解决:
该程序具有一个面板对象数组,每次添加新面板时都会增长。当它达到 400 个面板时,它会删除最旧的面板以释放一些内存。
我不明白的是:
当我使用上述代码时,内存使用仍然不断增加......有人可以解释一下为什么我必须先处理面板再将面板设置为空吗?
为了解决滚动 bug,我使用了一个面板 HistoryPanel,在其中放置了当前的面板:
该程序具有一个面板对象数组,每次添加新面板时都会增长。当它达到 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
当我使用上述代码时,内存使用仍然不断增加......有人可以解释一下为什么我必须先处理面板再将面板设置为空吗?
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
谢谢您的提前帮助!
编辑 @ 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;
}
为了解决滚动 bug,我使用了一个面板 HistoryPanel,在其中放置了当前的面板:
HistoryPanel.Controls.Add(currentPanel);
然后我添加了所有的控件:用户名、当前时间和头像。
为了保存面板,我在创建空间后将其添加到面板数组中,如上所示:
panels[panels.Length-1] = currentPanel;
我使用数组是因为历史记录会显示最新的记录在顶部。为了做到这一点,每次我都必须将所有面板向下移动80个像素。
GC.GetTotalMemory(true)
。 - Tim SchmelterList<Panel>
) - Steve BList<>
),它会很好地适应你的代码:panels.RemoveAt(0);
,然后你就完成了。 - Alex