求从线程执行一个很长的Thread.Sleep()UI线程又不卡死的办法

a091003040421 2014-08-05 08:43:29
namespace WindowsFormsApplication1
{


public partial class Form1 : Form
{
private delegate void MyDelegate();
int num = 0;
Thread t1;
public Form1()
{
InitializeComponent();

}
private void button1_Click(object sender, EventArgs e)
{
t1 = new Thread(SetText);
t1.IsBackground = true;
t1.Start();
}

private void SetText()
{
MyDelegate d1 = StartDelegate;
while (true)
{
textBox1.Invoke(d1);
}
}
void StartDelegate()
{
//textBox1.Text = num++.ToString();
Thread.Sleep(10000);
}

private void button2_Click(object sender, EventArgs e)
{
t1.Suspend();
}
}
}
...全文
498 6 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
风吹腚腚凉 2014-08-07
  • 打赏
  • 举报
回复
引用 3 楼 Z65443344 的回复:
Thread.Sleep(10000); 写到while里面,而不要写到委托里面 写到委托里,委托是主线程去调用,相当于主线程sleep
真相
风吹腚腚凉 2014-08-07
  • 打赏
  • 举报
回复
引用 2 楼 caozhy 的回复:
之所以死,是因为 while (true) { textBox1.Invoke(d1); } 在主线程写这个当然死。 另外 t1.Suspend(); 不要这么写,停止或者挂起线程让线程自己做。
纠正一下 textBox1.Invoke(d1); 这句是在主线程运行的,而不是 while (true) { textBox1.Invoke(d1); } 在主线程与行的。
effun 2014-08-07
  • 打赏
  • 举报
回复
用Timer吧
於黾 2014-08-07
  • 打赏
  • 举报
回复
Thread.Sleep(10000); 写到while里面,而不要写到委托里面 写到委托里,委托是主线程去调用,相当于主线程sleep
threenewbee 2014-08-06
  • 打赏
  • 举报
回复
之所以死,是因为 while (true) { textBox1.Invoke(d1); } 在主线程写这个当然死。 另外 t1.Suspend(); 不要这么写,停止或者挂起线程让线程自己做。
tanta 2014-08-05
  • 打赏
  • 举报
回复
把sleep的地方改为 DateTime lastTime = DateTime.Now; DateTime currTime = lastTime; while ((currTime - lastTime).Ticks < 10000) { Application.DoEvents(); }

111,093

社区成员

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

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

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