首页 > 代码库 > 搞定多线程自动代码生成控件的问题,解决了参数不匹配异常
搞定多线程自动代码生成控件的问题,解决了参数不匹配异常
直接帖核心代码
private void button1_Click(object sender, EventArgs e)
{
this.tableLayoutPanel1.Controls.Clear();
this.tableLayoutPanel1.RowCount = 10;
this.tableLayoutPanel1.ColumnCount = 10;
Button btn;
List<Button> lst = new List<Button>();
Thread objThread3 = new Thread(() =>
{
for (int i = 0; i < 50; i++)
{
btn = new Button()
{
Name = i.ToString(),
Text = i.ToString(),
Size = new Size(50, 50),
};
lst.Add(btn);
}
if (this.tableLayoutPanel1.InvokeRequired)
{
Thread.Sleep(500);
this.tableLayoutPanel1.Invoke(new Action<List<Button>>(setControls),lst);
}
});
objThread3.IsBackground = true;//设置为后台线程(通常都要这样设置)
objThread3.Start();
}
private void setControls(List<Button> lst )
{
tableLayoutPanel1.Controls.AddRange(lst.ToArray());
}
搞定多线程自动代码生成控件的问题,解决了参数不匹配异常