winform 容器内存泄漏
Posted zutian
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了winform 容器内存泄漏相关的知识,希望对你有一定的参考价值。
循环中释放容器时调用Dispose()方法会销毁对象,导致容器的个数变化。
正确示例
//方法一
for (int i = this.flowLayoutPanel1.Controls.Count-1; i >=0; i--) this.flowLayoutPanel1.Controls[i].Click -= btnClick; this.flowLayoutPanel1.Controls[i].Dispose();
//方法二
int ctlNum = this.flowLayoutPanel1.Controls.Count;
for (int i = 0; i < ctlNum; i++)
this.flowLayoutPanel1.Controls[0].Click -= btnClick;
this.flowLayoutPanel1.Controls[0].Dispose();
错误示例
两种方式都因在循环中修改了循环条件,导致内存泄漏
foreach (var ctl in this.flowLayoutPanel1.Controls)
(ctl as Control).Click -= btnClick;
(ctl as Control).Dispose();
(ctl as Control).Click -= btnClick;
(ctl as Control).Dispose();
for (int i = 0; i < this.flowLayoutPanel1.Controls.Count; i++)
this.flowLayoutPanel1.Controls[i].Click -= btnClick;
this.flowLayoutPanel1.Controls[i].Dispose();
this.flowLayoutPanel1.Controls[i].Click -= btnClick;
this.flowLayoutPanel1.Controls[i].Dispose();
以上是关于winform 容器内存泄漏的主要内容,如果未能解决你的问题,请参考以下文章
FastMM 报告 C++ Builder 6 中 STL 容器的内存泄漏