C# - How to speed up the addition of panels to a tableLayoutPanel?

时间:2016-02-12 19:25:12

标签: c# multithreading panel tablelayoutpanel

I have a 50x50 tableLayoutPanel with all the cells empty when the program starts. Them, after clicking new or Load, I add panels to all the cells, with specific background images. The problem is that it is way too slow to perform that, and even after the all thing is set, the program lags while scrolling...

Here's the code that adds the panels to the cells:

private void startLayout(object sender, EventArgs e)
    {
        BeginControlUpdate(tableLayoutPanel1);
        LoadCellsBar.Visible = true;
        Panel p;

        for (int Row = 0; Row <= tableLayoutPanel1.RowCount - 1; Row++)
        {
            for (int Column = 0; Column <= tableLayoutPanel1.ColumnCount - 1; Column++)
            {
                p = new Panel();
                p.BackgroundImageLayout = ImageLayout.Stretch;
                p.Dock = DockStyle.Fill;
                p.Margin = new Padding(1);
                p.BackgroundImage = Symbols.Clearbm;
                p.MouseClick += new MouseEventHandler(Panel_click);
                p.MouseHover += new System.EventHandler(this.ShowCoord);
                p.ContextMenuStrip = MenuPanels;
                tableLayoutPanel1.Controls.Add(p);
            }
            LoadCellsBar.PerformStep();
        }
        LoadCellsBar.Visible = false;
        LoadCellsBar.Value = 0;
        tableLayoutPanel1.Visible = true;
        EndControlUpdate(tableLayoutPanel1);
    }

I'm not doing suspend layout beacouse it wasn't working and instead using what was recomended in this thread Parallel Generation of UI. I've also tried to set doubleBuffer to true like proposed in here .Net TableLayoutPanel – Clearing Controls is Very Slow and it isn't changing the behavior os the program...

Is there any other way to do this, like running the panel in a different thread or am I doing something wrong in the code itself?

0 个答案:

没有答案