private delegate void FlushClient(); //委托 private void Form1_Load(object sender, EventArgs e) { Thread thread = new Thread(ThreadFunction); //创建一个线程 thread.IsBackground = true; thread.Start(); } private void ThreadFunction() { while (true) { FlushClient fc = new FlushClient(CrossThreadFlush); //使用委托 this.BeginInvoke(fc); Thread.Sleep(1000); } } private void CrossThreadFlush() { label1.Text = (DateTime.Now.ToString() + " "); Thread.Sleep(1000); }
要点1:因为用到Thread.Sleep(),主程序将会在Sleep期间卡死,所以要用多线程处理,让创建的线程执行Sleep。
要点2:你要在多线程内控制winform的控件,必须要借助到委托来访问,这是为了防止两个线程访问同一控件而出错,更详细的解释在这