方法一:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// 重点
Control.CheckForIllegalCrossThreadCalls = false;
}
private void Form1_Load(object sender, EventArgs e)
{
Thread thread = new Thread(ThreadFuntion);
thread.IsBackground = true;
thread.Start();
}
private void ThreadFuntion()
{
while (true)
{
this.textBox1.Text = DateTime.Now.ToString();
Thread.Sleep(1000);
}
}
}
方法二:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private delegate void FlushClient();//代理
private bool bShouldStop = false;
// 开始按钮
private void button1_Click(object sender, EventArgs e)
{
Thread thread = new Thread(CrossThreadFlush);
bShouldStop = false;
thread.IsBackground = true;
thread.Start();
}
// 结束按钮
private void button2_Click(object sender, EventArgs e)
{
bShouldStop = true;
}
// 线程函数
private void CrossThreadFlush()
{
//将代理绑定到方法
FlushClient fc = new FlushClient(ThreadFuntion);
while (bShouldStop == false)
{
this.BeginInvoke(fc);
Thread.Sleep(1000);
}
}
// 运行刷新函数
private void ThreadFuntion()
{
this.label1.Text = DateTime.Now.ToString();
// 更多的刷新都可以放到这里
//
}
}