在winform窗体上拖一个flowLayoutPane,一个Button,一个用户控件UcControl,用户控件上放几十个子控件
private void button1_Click(object sender, EventArgs e) { try { DateTime startTime = DateTime.Now; flowLayoutPanel1.Controls.Clear(); for (int i = 0; i < Controlcount; i++) { UcControl v = new UcControl(); v.Width = 275; v.Height = 120; flowLayoutPanel1.Controls.Add(v); } slExecutedTime.Text = (DateTime.Now - startTime).ToString(); } catch (Exception exception) { Console.WriteLine(exception); throw; } }
使劲点按钮,过一会弹出创建句柄出错。解决办法,加上红色部分就好了,再使劲点也不会出问题。
private void button1_Click(object sender, EventArgs e) { try { DateTime startTime = DateTime.Now; for (int i = 0; i < flowLayoutPanel1.Controls.Count; i++) { DeleteChilds(flowLayoutPanel1.Controls[i]); } GC.Collect(); flowLayoutPanel1.Controls.Clear(); for (int i = 0; i < Controlcount; i++) { UcControl v = new UcControl(); v.Width = 275; v.Height = 120; flowLayoutPanel1.Controls.Add(v); } slExecutedTime.Text = (DateTime.Now - startTime).ToString(); } catch (Exception exception) { Console.WriteLine(exception); throw; } }
private void DeleteChilds(Control control) { foreach (Control v in control.Controls) { if (v.Controls.Count>0) { DeleteChilds(v); } v.Dispose(); } }