通过线程实时获取当前时间

来源:互联网 发布:淘宝试用的东西要还吗 编辑:程序博客网 时间:2024/04/28 18:06
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.Threading;namespace com{    public partial class FrmDemo2 : Form    {        public FrmDemo2()        {            InitializeComponent();            this.Init();        }        protected void Init()        {            this.Text = "使用System.Threading.Timer动态显示当前时间";            //Callback:一个 TimerCallback 委托,表示要执行的方法。            //State:一个包含回调方法要使用的信息的对象,或者为空引用(Visual Basic 中为 Nothing)。            //dueTime:调用 callback 之前延迟的时间量(以毫秒为单位)。指定 Timeout.Infinite 以防止计时器开始计时。指定零 (0) 以立即启动计时器。            //Period:调用 callback 的时间间隔(以毫秒为单位)。指定 Timeout.Infinite 可以禁用定期终止。            System.Threading.Timer timer = new System.Threading.Timer(new TimerCallback(run), null, 0, 1000);            this.labTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");        }        private void run(object obj)        {            if (this.labTime.InvokeRequired)            {                delSetTime delsettime = new delSetTime(setTime);                this.Invoke(delsettime);            }            else            {                this.labTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");            }        }        protected delegate void delSetTime();        private void setTime()        {            this.labTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");        }    }}

0 0