码迷,mamicode.com
首页 > Windows程序 > 详细

winform 容器内存泄漏

时间:2019-07-25 00:50:57      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:调用   btn   释放   foreach   两种   条件   i++   内存   错误   

循环中释放容器时调用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();
            }
 
            for (int i = 0; i < this.flowLayoutPanel1.Controls.Count; i++)
            {
                this.flowLayoutPanel1.Controls[i].Click -= btnClick;
                this.flowLayoutPanel1.Controls[i].Dispose();
            }
 

 

winform 容器内存泄漏

标签:调用   btn   释放   foreach   两种   条件   i++   内存   错误   

原文地址:https://www.cnblogs.com/zutian/p/11241505.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!