简单写了下
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public delegate void mydelegate();
public delegate void mydelegate2(string lblid,int i);
private object lockObj = new object();
int threadid;
int widht = 11;
private void Form1_Shown(object sender, EventArgs e)
{
}
private void mydelegatePro()
{
widht += 10;
threadid++;
Label lbl = new Label();
lbl.Name = "lbl" + threadid.ToString();
lbl.Top = widht;
this.Controls.Add(lbl);
Application.DoEvents();
}
private void mydelegatePro2(string lblid,int i)
{
Control con = this.Controls[lblid];
Label lbl = (Label)con;
lbl.Text = i.ToString();
Application.DoEvents();
}
private void NewThread()
{
this.BeginInvoke(new mydelegate(mydelegatePro)); string lblid = "lbl" + threadid.ToString();
int i = 0;
while (true)
{
i++;
lock (lockObj)
{ this.BeginInvoke(new mydelegate2(mydelegatePro2), new object[] { lblid, i });
}
Thread.Sleep(200);
if (i >= 10) break;
}
}
private void button1_Click(object sender, EventArgs e)
{
Thread thread = new Thread(new ThreadStart(NewThread));
thread.IsBackground = true;
thread.Start();
Thread thread2 = new Thread(new ThreadStart(NewThread));
thread2.IsBackground = true;
thread2.Start();
}
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public delegate void mydelegate();
public delegate void mydelegate2(string lblid,int i);
private object lockObj = new object();
int threadid;
int widht = 11;
private void Form1_Shown(object sender, EventArgs e)
{
}
private void mydelegatePro()
{
widht += 10;
threadid++;
Label lbl = new Label();
lbl.Name = "lbl" + threadid.ToString();
lbl.Top = widht;
this.Controls.Add(lbl);
Application.DoEvents();
}
private void mydelegatePro2(string lblid,int i)
{
Control con = this.Controls[lblid];
Label lbl = (Label)con;
lbl.Text = i.ToString();
Application.DoEvents();
}
private void NewThread()
{
this.BeginInvoke(new mydelegate(mydelegatePro)); string lblid = "lbl" + threadid.ToString();
int i = 0;
while (true)
{
i++;
lock (lockObj)
{ this.BeginInvoke(new mydelegate2(mydelegatePro2), new object[] { lblid, i });
}
Thread.Sleep(200);
if (i >= 10) break;
}
}
private void button1_Click(object sender, EventArgs e)
{
Thread thread = new Thread(new ThreadStart(NewThread));
thread.IsBackground = true;
thread.Start();
Thread thread2 = new Thread(new ThreadStart(NewThread));
thread2.IsBackground = true;
thread2.Start();
}
}
string lblid = "lbl" + threadid.ToString();threadid有可能是一样的。同为2
通地调试跟踪 确保threadid不一样的时候也 无法显示第二个Label
lbl.Top = widht;