有一个面板,我想向k
它添加控件。我想为每个控件指定任务以供以后使用。所以 :
*在下面更新一些其他代码;请看第三个代码*
*****Update*****
Child Control : PacketData (can be a Button)
Main Control : panel
PlaceData() changes the left and top randomly.
我曾经这样做过:
Parallel.For(0, k, (m) =>
{
tasks[m] = Task.Factory.StartNew(() =>
{
PacketData data = new PacketData();
data.StartTime = sw.ElapsedMilliseconds;
lock (data_adding_lock)
{
IAsyncResult iar = panel1.BeginInvoke(new MethodInvoker(()=>{
PlaceData(ref data);
panel1.Controls.Add(data);
}));
panel1.EndInvoke(iar);
while (iar.IsCompleted ==false ) ;
}
});
});
它有时工作得很好,但有时却不行,例如,有时它只PacketData
向面板 Control 添加一个。我失去了比赛条件吗?
我也试过这个,但没有工作......
Parallel.For(0, k, (m) =>
{
tasks[m] = Task.Factory.StartNew(() =>
{
PacketData data;
lock (data_instancing_lock) {
data = new PacketData();}
data.StartTime = sw.ElapsedMilliseconds;
IAsyncResult iar = panel1.BeginInvoke(new MethodInvoker(()=>{
PlaceData(ref data);
lock(data_adder_lock){
panel1.Controls.Add(data);}
}));
panel1.EndInvoke(iar);
//PlaceData(ref data);
});
});
*更新* *
这是另一个例子(它不工作......)
object l1 = new object();
object l2 = new object();
private delegate void AdderDel(Button bb);
public Form1()
{
InitializeComponent();
}
private void AddControl(Button x)
{
lock (l2)
{
this.Controls.Add(x);
}
}
private void Place(ref Button btn)
{
Random rnd = new Random();
int x = rnd.Next(0, this.Width-100);
int y = rnd.Next(0, this.Height-100);
btn.Left = x;
btn.Top = y;
}
private void button1_Click(object sender, EventArgs e)
{
int n = 5;
Task[] t = new Task[n];
AdderDel ad = new AdderDel(AddControl);
Parallel.For(0, n, (k) =>
{
t[k] = Task.Factory.StartNew(() =>
{
Button b = new Button();
b.Text = k.ToString();
b.Height = 50;
Place(ref b);
this.BeginInvoke(ad, b);
});
});
}
为什么?