执行线程,不卡死主线程

private void button1_Click(object sender, EventArgs e)
{
int i = 0;
Thread th = new Thread(new ThreadStart(() =>
{
while (true)
{
// Thread.Sleep(1000);//繁琐的操作,或者IO等待放在这个线程里面操作
this.Invoke(new Action(() =>
{//当需要操作界面元素时,需要用Invoke,注意这里面不能有繁琐的操作
txtBox.Text = (i++).ToString();
//Thread.Sleep(1000);如果这么写,就会卡住主线程
}));
}
}));
th.IsBackground = true;//一定要标记为后台线程,这样这个线程才能在你的主线程停止后自动停止
th.Start();
}

原文地址:https://www.cnblogs.com/mengyirensheng/p/4109526.html