不断添加和删除flowlayoutpanel winforms

时间:2014-11-20 14:00:45

标签: c# winforms flowlayoutpanel

我有一个c#win表单应用程序,其中包含flowLayoutPanel

我需要每秒更新此面板中的所有孩子。

这是我当前的代码,每1秒在系统计时器中调用一次:

   public void RefreshReceiversPage()
    {
        if (checkBox_enableReceivers.Checked)
        {
            var receivers = OutgoingReceiverManager.GetCopyOfActiveRecieverHolders();

            for (int i = 0; i < flowLayoutPanel_receivers.Controls.Count; i++)
            {
                var tmp = flowLayoutPanel_receivers.Controls[i];
                flowLayoutPanel_receivers.Controls[i].Dispose();
                tmp.Dispose();
            }
            flowLayoutPanel_receivers.Controls.Clear();

            foreach (var item in receivers.ToList())
            {
                var tmpUc = new ucReceiverItem(item);
                if (flowLayoutPanel_receivers != null)
                {
                    try
                    {
                        flowLayoutPanel_receivers.Controls.Add(tmpUc);
                    }
                    catch
                    {
                    }
                }
            }
            receivers = null;
        }            
    }

现在这段代码完美地工作了大约2分钟,然后我突然开始得到error creating window handle因此,我尝试捕获上面代码的原因。

但是在发生这种情况之后,窗格视图变得很有趣,我无法在不重新启动程序的情况下恢复它。

我搜索了高低,我似乎无法找到抛出异常的任何内容?

我能想到的一切是,我可能没有正确处理对象,而且内存耗尽了吗?

有人有任何建议或解决方案吗?

编辑:

这里是UCRecieverItem:

public partial class ucReceiverItem : UserControl
{
    public ucReceiverItem(ReceiverHolder item)
    {
        InitializeComponent();
        ConstructItem(item);
        item = null;
    }

    private void ConstructItem(ReceiverHolder item)
    {
        label_name.Text = item.ReceiverDb.Name;
        label_numberOfConnections.Text = item.ReceiverOutgoingConnectionManager.GetNumberOfConnections().ToString();
        label_mrFilters.Text = item.ReceiverDb.MrFilters;
        label_multipleConnections.Text = item.ReceiverDb.MultipleConnections.ToString();
        //
        int count = item.GetActiveBufferCount();
        int size = item.GetActiveBufferSize();
        //
        label_bufferCount.Text = count + @" / " + size;
        progressBar_buffer.Maximum = size;
        progressBar_buffer.Minimum = 0;
        progressBar_buffer.Value = count;
    }
}

1 个答案:

答案 0 :(得分:3)

此代码存在问题:

for (int i = 0; i < flowLayoutPanel_receivers.Controls.Count; i++)
{
  var tmp = flowLayoutPanel_receivers.Controls[i];
  flowLayoutPanel_receivers.Controls[i].Dispose();
  tmp.Dispose();
}
flowLayoutPanel_receivers.Controls.Clear();

它只在容器中处理控件的一半。另一半被Controls.Clear();调用删除,但这些控件不会被处理 - 所以它们仍然存在并且正在耗尽内存。

这样做每一秒都会解决问题:这可能是很多控制因素。

直接解决方法是妥善处理控件:

while (flowLayoutPanel_receivers.Controls.Count > 0) {
  flowLayoutPanel_receivers.Controls[0].Dispose();
}

在此之后,我会质疑每秒都需要这样做 - 对于用户来说,这似乎是一个恶劣的环境。