做winform程序,避免不了的要在线程里控制窗体上的控件,直接在子线程里操作控件会报错“线程间操作无效,从不是创建控件***的线程访问它”。
解决方法:
private void Form1_Load(object sender, EventArgs e)
{
Thread t1 = new Thread(t1_clock);
t1.IsBackground = true;
t1.Start();
}
public void t1_clock()
{
while (true)
{
//保险起见,可以加上这个判断
if (this.IsDisposed || !this.IsHandleCreated)
{
continue;
}
if (this.InvokeRequired)
{
this.Invoke(new Action(() =>
{
this.textBox1.Text = DateTime.Now.ToString("G");
}));
}
Thread.Sleep(1000);
}
}
标签:控件,Thread,clock,C#,t1,线程 From: https://www.cnblogs.com/xujiecnblogs/p/17356744.html