C#里面的三种定时计时器:Timer

2023-09-21 14:50:25

在.NET中有三种计时器:
1、System.Windows.Forms命名空间下的Timer控件,它直接继承自Componet。Timer控件只有绑定了Tick事件和设置Enabled=True后才会自动计时,停止计时可以用Stop()方法控制,通过Stop()停止之后,如果想重新计时,可以用Start()方法来启动计时器。Timer控件和它所在的Form属于同一个线程;
2、System.Timers命名空间下的Timer类。System.Timers.Timer类:定义一个System.Timers.Timer对象,然后绑定Elapsed事件,通过Start()方法来启动计时,通过Stop()方法或者Enable=false停止计时。AutoReset属性设置是否重复计时(设置为false只执行一次,设置为true可以多次执行)。Elapsed事件绑定相当于另开了一个线程,也就是说在Elapsed绑定的事件里不能访问其它线程里的控件(需要定义委托,通过Invoke调用委托访问其它线程里面的控件)。
3、System.Threading.Timer类。定义该类时,通过构造函数进行初始化。
在上面所述的三种计时器中,第一种计时器和它所在的Form处于同一个线程,因此执行的效率不高;而第二种和第三种计时器执行的方法都是新开一个线程,所以执行效率比第一种计时器要好,因此在选择计时器时,建议使用第二种和第三种。

下面是三种定时器使用的例子:

1、Timer控件

设计界面:

后台代码:

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;

namespace TimerDemo
{
    public partial class FrmMain : Form
    {
        //定义全局变量
        public int currentCount = 0;
        public FrmMain()
        {
            InitializeComponent();
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            //设置Timer控件可用
            this.timer.Enabled = true;
            //设置时间间隔(毫秒为单位)
            this.timer.Interval = 1000;
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            currentCount += 1;
            this.txt_Count.Text = currentCount.ToString().Trim();
        }

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

        private void btn_Stop_Click(object sender, EventArgs e)
        {
            //停止计时
            this.timer.Stop();
        }
    }
}

 

2、System.Timers.Timer

设计界面:

后台代码:

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;

namespace TimersTimer
{
    public partial class FrmMain : Form
    {
        //定义全局变量
        public int currentCount = 0;
        //定义Timer类
        System.Timers.Timer timer;
        //定义委托
        public delegate void SetControlValue(string value);

        public FrmMain()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            InitTimer();
        }

        /// <summary>
        /// 初始化Timer控件
        /// </summary>
        private void InitTimer()
        {
            //设置定时间隔(毫秒为单位)
            int interval = 1000;
            timer = new System.Timers.Timer(interval);
            //设置执行一次(false)还是一直执行(true)
            timer.AutoReset = true;
            //设置是否执行System.Timers.Timer.Elapsed事件
            timer.Enabled = true;
            //绑定Elapsed事件
            timer.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 += 1;
                this.Invoke(new SetControlValue(SetTextBoxText),currentCount.ToString());
            }
            catch (Exception ex)
            {
                MessageBox.Show("执行定时到点事件失败:" + ex.Message);
            }
        }

        /// <summary>
        /// 设置文本框的值
        /// </summary>
        /// <param name="strValue"></param>
        private void SetTextBoxText(string strValue)
        {
            this.txt_Count.Text = this.currentCount.ToString().Trim();
        }

        private void btn_Start_Click(object sender, EventArgs e)
        {
            timer.Start();
        }

        private void btn_Stop_Click(object sender, EventArgs e)
        {
            timer.Stop();
        }
    }
}

 

3、System.Threading.Timer

设计界面:

后台代码:

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 Threading.Timer
{
    public partial class FrmMain : Form
    {
        //定义全局变量
        public int currentCount = 0;
        //定义Timer类
        System.Threading.Timer threadTimer;
        //定义委托
        public delegate void SetControlValue(object value);

        public FrmMain()
        {
            InitializeComponent();
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            InitTimer();
        }

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

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

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

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

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

 

更多推荐

Qt(day5)

思维导图将登录操作和数据库绑定mywnd.h#ifndefMYWND_H#defineMYWND_H#include<QMainWindow>#include<QLabel>#include<QLineEdit>#include<QPushButton>#include<QDebug>#include<QMessage

程序人生,中秋共享

程序人生,中秋共享随着科技的迅速发展,中秋节也悄然发生了变化。在这个传统的团圆节日里,程序人生与中秋共享形成了新的气象。在本文中,我将结合自己的职业经历,探讨程序人生与中秋共享之间的联系与意义。【中秋与程序人生的交融】作为程序员,我们每天都在和代码打交道,通过一行行指令来构建世界。然而,在这个机械化的过程中,我们也不忘

LLM预训练之RLHF(一):RLHF及其变种

在ChatGPT引领的大型语言模型时代,国内外的大模型呈现爆发式发展,尤其是以年初的LLaMA模型为首的开源大模型和最近百川智能的baichuan模型,但无一例外,都使用了「基于人类反馈的强化学习」(RLHF)来提升语言模型的性能,并在模型重注入了人类的偏好,以提高模型的有用性和安全性。不过RLHF也早已更新换代,我们

【Spring Boot】操作Redis数据结构

🌿欢迎来到@衍生星球的CSDN博文🌿🍁本文主要学习【SpringBoot】操作Redis数据结构🍁🌱我是衍生星球,一个从事集成开发的打工人🌱⭐️喜欢的朋友可以关注一下🫰🫰🫰,下次更新不迷路⭐️💠作为一名热衷于分享知识的程序员,我乐于在CSDN上与广大开发者交流学习。💠我希望通过每一次学习,让更多读

【MySql】1- 基础篇(上)

文章目录1.1前言1.2基础架构1.2.1MySql基本架构示意图1.2.2SQL语句执行顺序1.3日志系统:一条SQL更新语句如何执行1.3.1两阶段提交1.4事务隔离1.4.1隔离性与隔离级别1.4.2事务隔离的实现-展开说明“可重复读”1.4.3事务的启动方式1.5深入浅出索引1.5.1索引常见模型1.5.1In

双周赛113(枚举、分类讨论 + 二分查找、枚举值域两数之和、换根DP)

文章目录双周赛113[2855.使数组成为递增数组的最少右移次数](https://leetcode.cn/problems/minimum-right-shifts-to-sort-the-array/)暴力枚举贪心O(n)[2856.删除数对后的最小数组长度](https://leetcode.cn/problem

91. 面试官:JSONP的原理是什么?

91期1.JSONP的原理是什么?2.css优先级是什么样的?3.display的值有哪些,分别有什么作用?上面问题的答案会在第二天的公众号(程序员每日三问)推文中公布90期问题及答案1.什么是前后端分离,好处是什么?前后端分离是一种软件架构模式,它将前端和后端开发分离为两个独立的工作流程和技术栈,它们通过API或We

Java 中 jps 命令

jps(JavaVirtualMachineProcessStatusTool)是Java开发工具包(JDK)中的一个命令行工具,用于查看Java虚拟机(JVM)中运行的Java进程的状态信息。它通常用于检查正在运行的Java应用程序的进程ID(PID)和相关信息,这对于调试和性能监控非常有用。以下是jps命令的使用示

LeetCode 之 长度最小的子数组

算法模拟:AlgorithmVisualizer在线工具:C++在线工具如果习惯性使用VisualStudioCode进行编译运行,需要C++11特性的支持,可参考博客:VisualStudioCode支持C++11插件配置长度最小的子数组LeetCode长度最小的子数组问题:给定一个含有n个正整数的数组和一个正整数t

CAN总线物理层

本文的目的并不是为了介绍或普及CAN总线相关知识,而是为了了解CAN总线,进而为CAN通信一致性测试做知识储备。CAN,控制器局域网,全称:ControllerAreaNetwork。1986年,由德国Bosch公司为汽车开发的网络技术,主要用于汽车的监测与控制,目的为适应汽车“减少线束的数量”、“通过多个网络进行大量

vue学习-03vue父子组件与ref属性

本篇开始,我们将复习一下上篇的组件引入:App.vue<template><div><imgsrc="./assets/logo.png"alt="logo"><!--编写组件标签--><School></School><Student></Student></div></template><script>//引入组件

热文推荐