多线程问题,子线程访问主线程控件,修改内容不实时!

hanqing_liu 2012-09-19 04:13:18
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();
}
}
}
需求:需要界面上控件值同时实时改变,互不影响!
求解答!
...全文
125 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
yangfan1981 2012-09-19
  • 打赏
  • 举报
回复
没有测试你说的效果。
但我的理解是,线程调度由系统控制,不是休眠300ms之后就立即执行的。
hanqing_liu 2012-09-19
  • 打赏
  • 举报
回复
解决了。分享下
public delegate void SetTextHander(Label lbl, int j);

Thread t1, t2;
private void button1_Click(object sender, EventArgs e)
{
t1 = new System.Threading.Thread(new ThreadStart(() => SetText(lbl1, 400)));
t1.IsBackground = true;
t1.Start();

t2 = new System.Threading.Thread(new ThreadStart(() => SetText(lbl2, 500)));
t2.IsBackground = true;
t2.Start();
}

public void SetText(Label lbl, int secends)
{
for (int i = 0; i < 1000; i++)
{
Thread.Sleep(secends);
SetLblText(lbl, i);
}
}

public void SetLblText(Label lbl, int j)
{
if (this.InvokeRequired)
{
SetTextHander sth = new SetTextHander(SetLblText);
this.BeginInvoke(sth, new object[] { lbl, j });
}
else
{
lock (lbl)
{
lbl.Text = j.ToString();
}
}
}
hanqing_liu 2012-09-19
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 的回复:]
C# code

for (int i = 0; i < 10; i++)
{
lbl.Text = i.ToString();
}
[/Quote]
去掉Thread.Sleep(300);
之后看不出来效果,不去掉的话怎么处理
bdmh 2012-09-19
  • 打赏
  • 举报
回复

for (int i = 0; i < 10; i++)
{
lbl.Text = i.ToString();
}

110,571

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧