日期:2014-05-17  浏览次数:21050 次

多线程问题,子线程访问主线程控件,修改内容不实时!
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之后就立即执行的。