我对线程入门理解

之前有个朋友问我在windows窗体上拖一个LABEL,然后在窗体加载后,取当前时间给它,这样为什么不能让LABEL和系统的时间同步变化。实现这个其实有两种方法,有非常简单的是用Timer控件。然而,一直没有用过线程,找了点资料还是可以实现的:

Code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
}

private void Form3_Load(object sender, EventArgs e)
{
System.Threading.ThreadStart time
= new System.Threading.ThreadStart(TimeStart);
System.Threading.Thread th1
= new System.Threading.Thread(time);
//添加这个属性才可以实现跨控件使用进程
Control.CheckForIllegalCrossThreadCalls = false;
th1.Start();
System.Threading.Thread.Sleep(
1000);

}


private void TimeStart()
{
while (!false)
{
//让当前进程休眠一秒再显示LABEL
System.Threading.Thread.Sleep(1000);
this.label1.Text = System.DateTime.Now.ToString();
}
}
}
}
原文地址:https://www.cnblogs.com/shineqiujuan/p/1312788.html