C# 定时器的三种实现方式:Timer

本文对比了.NET平台下的三种计时器:System.Windows.Forms.Timer、System.Timers.Timer和System.Threading.Timer的功能特性及适用场景,并提供了具体的代码实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Timer实现

1.System.Timers.Timer

这个Timer是使用线程池中的线程去执行任务的,既然是使用线程池里的线程,就必须在访问任务用到的资源的时候,对线程进行同步!可以指定某个线程去执行任务。System.Timers.Timer类:定义一个System.Timers.Timer对象,然后绑定Elapsed事件,通过Start()方法来启动计时,通过Stop()方法或者Enable=false停止计时。AutoReset属性设置是否重复计时(设置为false只执行一次,设置为true可以多次执行)。Elapsed事件绑定相当于另开了一个线程,也就是说在Elapsed绑定的事件里不能访问其它线程里的控件(需要定义委托,通过Invoke调用委托访问其它线程里面的控件)。

2.System.Threading.Timer

和1中的Timer类似也是使用线程池中的线程去执行任务的,但是不可以指定的某个线程去执行任务。定义该类时,通过构造函数进行初始化。System.Windows.Forms和它所在的Form处于同一个线程,因此执行的效率不高;而另外两种计时器执行的方法都是新开一个线程,所以执行效率要好,因此在选择计时器时,建议使用第一种和第二种

3.System.Windows.Forms.Timer

System.Windows.Forms命名空间下的Timer控件,它直接继承自Componet。Timer控件只有绑定了Tick事件和设置Enabled=True后才会自动计时,停止计时可以用Stop()方法控制,通过Stop()停止之后,如果想重新计时,可以用Start()方法来启动计时器。Timer控件和它所在的Form属于同一个线程;该Timer的特点是执行任务的线程是专属于任务相关窗口的。决不能用这个Timer执行时间太长(例如几分之一秒)的任务,否则会造成界面无响应

例子,每秒计数+1,结果显示在文本框

  • 程序
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Timer_Test
{
    public partial class Form1 : Form
    {
        //定义System.Windows.Forms全局变量
        public int currentCount_Win = 0;

        //定义System.Timers.Timer全局变量
        public int currentCount_Tim = 0;
        //定义Timer类
        System.Timers.Timer timer_Tim;
        //定义委托
        public delegate void SetControlValue_Tim(string value);

        //定义System.Threading.Timer全局变量
        public int currentCount_Thr = 0;
        //定义Timer类
        System.Threading.Timer threadTimer;
        //定义委托
        public delegate void SetControlValue_Thr(object value);




        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //VS控制台输出
            //Console.WriteLine("每秒执行一次的定时任务,当前线程Id:{0}", Thread.CurrentThread.ManagedThreadId);

            //设置System.Windows.Forms Timer控件可用
            this.timer1.Enabled = true;
            //设置时间间隔(毫秒为单位)
            this.timer1.Interval = 1000;

            InitTimer_Tim();
            InitTimer_Thr();
        }
        #region**System.Windows.Forms**
        private void timer1_Tick(object sender, EventArgs e)
        {
            currentCount_Win += 1;
            this.textBox1.Text = currentCount_Win.ToString().Trim();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //开始计时
            this.timer1.Start();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //开始计时
            this.timer1.Stop();
        }




        #endregion
        #region**System.Timers.Timer**
        /// <summary>
        /// 初始化Timer控件
        /// </summary>
        private void InitTimer_Tim()
        {
            //设置定时间隔(毫秒为单位)
            int interval = 1000;
            timer_Tim = new System.Timers.Timer(interval);
            //设置执行一次(false)还是一直执行(true)
            timer_Tim.AutoReset = true;
            //设置是否执行System.Timers.Timer.Elapsed事件
            timer_Tim.Enabled = true;
            //绑定Elapsed事件
            timer_Tim.Elapsed += new System.Timers.ElapsedEventHandler(TimerUp);
        }

        /// <summary>
        /// Timer类执行定时到点事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TimerUp(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                currentCount_Tim += 1;
                this.Invoke(new SetControlValue_Tim(SetTextBoxText), currentCount_Tim.ToString());
            }
            catch (Exception ex)
            {
                MessageBox.Show("执行定时到点事件失败:" + ex.Message);
            }
        }

        /// <summary>
        /// 设置文本框的值
        /// </summary>
        /// <param name="strValue"></param>
        private void SetTextBoxText(string strValue)
        {
            this.textBox2.Text = this.currentCount_Tim.ToString().Trim();
        }
        private void button3_Click(object sender, EventArgs e)
        {
            timer_Tim.Start();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            timer_Tim.Stop();
        }

        #endregion
        #region**System.Threading.Timer**
        /// <summary>
        /// 初始化Timer类
        /// </summary>
        private void InitTimer_Thr()
        {
            threadTimer = new System.Threading.Timer(new TimerCallback(TimerUp), null, Timeout.Infinite, 1000);
        }

        /// <summary>
        /// 定时到点执行的事件
        /// </summary>
        /// <param name="value"></param>
        private void TimerUp(object value)
        {
            currentCount_Thr += 1;
            this.Invoke(new SetControlValue_Thr(SetTextBoxValue), currentCount_Thr);
        }

        /// <summary>
        /// 给文本框赋值
        /// </summary>
        /// <param name="value"></param>
        private void SetTextBoxValue(object value)
        {
            this.textBox3.Text = value.ToString();
        }

        /// <summary>
        /// 开始
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {
            //立即开始计时,时间间隔1000毫秒
            threadTimer.Change(0, 1000);
        }

        /// <summary>
        /// 停止
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button6_Click(object sender, EventArgs e)
        {
            //停止计时
            threadTimer.Change(Timeout.Infinite, 1000);
        }
        #endregion



    }
}
  • 窗体布局
    在这里插入图片描述
    在这里插入图片描述
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

猪悟道

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值