初学线程 想通过代码实现以下效果
winform上 分别有:label1 label2 button1
当我点击button1时 label1的text分别从1到100计数
label2的text分别从1到500计数计数同时开始
请给出代码 谢谢
winform上 分别有:label1 label2 button1
当我点击button1时 label1的text分别从1到100计数
label2的text分别从1到500计数计数同时开始
请给出代码 谢谢
在Button1_Click()中写
thread a=new thread(new ThreadStart(aa));
a.start();
thread b =new thread(new ThreadStart(bb));
b.start();
public void aa()
{
for(int i=0;i<100;i++)
{
label1.text=i.tostring()
}
}public void bb ()
{
for (int j=0;j<500;j++)
{
label2.text=j.tostring();
}
}
随手写的 ,可能有语法或者写法的错误,请更正;
{
for(int i=0;i <100;i++)
{
label1.text=i.tostring()
}
a.abort();
} public void bb ()
{
for (int j=0;j <500;j++)
{
label2.text=j.tostring();
}
b.abort();
} 这些不是在Button_Click ()中写的,这些是两个方法。呵呵。
对了还要在aa和bb的循环结束后关闭线程,分别见代码
例如
public delegate void addTxt(string str);
private void AddStr1(string str)
{
if (this.InvokeRequired)
{
addTxt haha = new addTxt(AddStr1);
this.Invoke(haha , new object[] { str });
}
else
label1.text=str;}将label1.text=i.tostring(); -〉替换成AddStr1(i.tostring);3楼的代码abort是多余的。
CheckForIllegalCrossThreadCalls容许子线呈随时更新ui
http://blog.csdn.net/jinjazz/archive/2007/12/10/1927126.aspx