C# Task.Factory多线程中如何将数值实时传递到UI显示
privatevoidbutton2_Click(objectsender,EventArgse){Taskt1=Task.Factory.StartNew(()=>k1...
private void button2_Click(object sender, EventArgs e)
{
Task t1 = Task.Factory.StartNew(() => k1());
Task t2 = Task.Factory.StartNew(() => k2());
Task.WaitAll(t1, t2);
}
void k1()
{
for (int i = 0; i < 100; i++)
{
Thread.Sleep(100);
label1.Text = i.ToString();
}
}
void k2()
{
for (int i = 0; i < 100; i++)
{
Thread.Sleep(100);
label2.Text = i.ToString();
}
} 展开
{
Task t1 = Task.Factory.StartNew(() => k1());
Task t2 = Task.Factory.StartNew(() => k2());
Task.WaitAll(t1, t2);
}
void k1()
{
for (int i = 0; i < 100; i++)
{
Thread.Sleep(100);
label1.Text = i.ToString();
}
}
void k2()
{
for (int i = 0; i < 100; i++)
{
Thread.Sleep(100);
label2.Text = i.ToString();
}
} 展开
1个回答
展开全部
要看是什么平台,如果是winform,你在另外一个线程不能直接访问窗体控件,可以用
private void button1_Click(object sender, EventArgs e)
{
Task t1 = Task.Factory.StartNew(() => k1());
Task t2 = Task.Factory.StartNew(() => k2());
}
void k1()
{
for (int i = 0; i < 100; i++)
{
Thread.Sleep(100);
this.Invoke(new Action(
() => { this.label1.Text = i.ToString(); }));
}
}
void k2()
{
for (int i = 0; i < 100; i++)
{
Thread.Sleep(100);
this.Invoke(new Action(
() => { this.label2.Text = i.ToString(); }));
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询