System.Timers.Timer的使用

来源:互联网 发布:网络的正面影响有哪些 编辑:程序博客网 时间:2024/05/16 10:33

做一个Winform项目时用到了定时器,用来显示时间。考虑到使用自带的Timers控件会有误差,所以就选择了System.Timers.Timer类来实现,实际效果是一样的。

        //3,定义底部时间显示Timer        public System.Timers.Timer tDayTime = null;        public delegate void ShowTime();//定义委托
        //显示时间        tDayTime = new System.Timers.Timer(1000);//实例化Timer类,设置间隔时间为1000毫秒;         tDayTime.Elapsed += new System.Timers.ElapsedEventHandler(tDayTime_Elapsed);//到达时间的时候执行事件;        tDayTime.AutoReset = true;//设置是执行一次(false)还是一直执行(true);         tDayTime.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件;
        /// <summary>        /// 显示时间        /// </summary>        /// <param name="source"></param>        /// <param name="e"></param>        public void tDayTime_Elapsed(object source, System.Timers.ElapsedEventArgs e)        {            try            {                FomatDatetime();            }            catch (Exception ex)            {                #region 异常处理                //将异常信息写入数据库                    MNG_LOG_INFOCS.LogGeneral("显示时间:", ex.ToString(), VideoWatch_Log_ReportType_En.App_WinFormStart);                //将异常信息写入日志()                ExceptionErrorLog("显示时间:" + ex.ToString());                #endregion            }        }
        /// <summary>        /// 显示时间        /// </summary>        public void FomatDatetime()        {            if (this.InvokeRequired)            {                this.BeginInvoke(new ShowTime(FomatDatetime));            }            else            {                System.TimeSpan diff = DateTime.Now.Subtract(startTime);                string runTime = "系统已经运行了:" + diff.Days + "天" + diff.Hours + "小时" + diff.Minutes + "分钟" + diff.Seconds + "秒";                this.toolStripStatuslblDayTime.Text = runTime;                this.statuslblDayTime.Text = "系统时间:" + DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss");            }        }
	
				
		
原创粉丝点击