读书人

多线程有关问题子线程访问主线程控件

发布时间: 2012-10-19 16:53:37 作者: rapoo

多线程问题,子线程访问主线程控件,修改内容不实时!
public delegate void SetTextHander(Label lbl);

private void button1_Click(object sender, EventArgs e)
{
Thread.Sleep(1000);
Thread t1 = new System.Threading.Thread(new ThreadStart(() => SetLblText(lbl1)));
t1.IsBackground = true;
t1.Start();
Thread t2 = new System.Threading.Thread(new ThreadStart(() => SetLblText(lbl2)));
t2.IsBackground = true;
t2.Start();
}

public void SetLblText(Label lbl)
{
if (this.InvokeRequired)
{
SetTextHander sth = new SetTextHander(SetLblText);
this.BeginInvoke(sth, lbl);
}
else
{
//Application.DoEvents();
for (int i = 0; i < 10; i++)
{
Thread.Sleep(300);
lbl.Text = i.ToString();
}
}
}
需求:需要界面上控件值同时实时改变,互不影响!
求解答!

[解决办法]

C# code
  for (int i = 0; i < 10; i++)  {  lbl.Text = i.ToString();  }
[解决办法]
没有测试你说的效果。
但我的理解是,线程调度由系统控制,不是休眠300ms之后就立即执行的。

读书人网 >C#

热点推荐