C# 定时器类实现1s定时器更新UI

1. 代码

//BaseTimer.cs

csharp 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace baseTimer
{
    //定义一个timer超时的委托
    public delegate void baseTimerDelegate(int cnt);

    
    class BaseTimer : IDisposable
    {
        private bool disposed = false;        
        private System.Threading.Timer timer1;
        private int period = 0;
        private int cnt = 0;
        private readonly object lockObject = new object();
        private bool isTimerRunning = false;
        private baseTimerDelegate timeoutDelegate;

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!disposed)
            {
                if (disposing)
                {
                    timer1?.Dispose();
                    timer1 = null;
                }
                disposed = true;
            }
        }

        public BaseTimer(baseTimerDelegate Delegate1,int period1)
        {
            period = period1;
            timeoutDelegate = Delegate1;
            timer1 = new System.Threading.Timer(TimerStepCallBack, null, Timeout.Infinite, period);
        }
        private void TimerStepCallBack(Object stateInfo)
        {
            cnt++;
            timeoutDelegate(cnt);
        }

        /// <summary>
        /// 启动定时器,每秒中断一次
        /// </summary>
        public void Start(int ms)
        {
            lock (lockObject)
            {
                if (!isTimerRunning)
                {
                    isTimerRunning = true;
                    cnt = 0;
                    // 立即启动,每秒触发一次
                    period = ms;
                    timer1.Change(0, ms);
                }
            }
        }

        /// <summary>
        /// 停止定时器
        /// </summary>
        public void Stop()
        {
            lock (lockObject)
            {
                if (isTimerRunning)
                {
                    timer1.Change(Timeout.Infinite, period);
                    isTimerRunning = false;
                    cnt = 0;
                    timeoutDelegate(cnt);
                }
            }
        }
    }
}

//Form1.cs

csharp 复制代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace baseTimer
{
    public partial class Form1 : Form
    {
        //定义一个timer超时的委托
        private baseTimerDelegate baseTimerDelegate1;
        private BaseTimer baseTimer1;

        public Form1()
        {
            InitializeComponent();

            baseTimerDelegate1 = new baseTimerDelegate(TimerBaseInvoke);
            baseTimer1 = new BaseTimer(baseTimerDelegate1,1000);
            // 订阅窗体关闭事件
            this.FormClosing += Form1_FormClosing;
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            baseTimer1?.Dispose();
        }

        private void TimerBaseInvoke(int cnt)
        {
            Invoke((EventHandler)(delegate
            {
                textBox1.Text = cnt.ToString();
            }));
        }

        private void buttonStart_Click(object sender, EventArgs e)
        {
            baseTimer1.Start(1000);
        }

        private void buttonStop_Click(object sender, EventArgs e)
        {
            baseTimer1.Stop();
        }
    }
}

2 . 效果

相关推荐
ss2733 分钟前
CompletionService:Java并发工具包
java·开发语言·算法
额呃呃8 分钟前
select和poll之间的性能对比
开发语言·算法
智航GIS8 分钟前
7.2 Try Except语句
开发语言·python
星轨初途9 分钟前
C++ string 类详解:概念、常用操作与实践(算法竞赛类)
开发语言·c++·经验分享·笔记·算法
二进制_博客9 分钟前
JWT权限认证快速入门
java·开发语言·jwt
程序员佳佳16 分钟前
026年AI开发实战:从GPT-5.2到Gemini-3,如何构建下一代企业级Agent架构?
开发语言·python·gpt·重构·api·ai写作·agi
橙露21 分钟前
Python 图形任意角度旋转完整解决方案:原理、实现与可视化展示
开发语言·python
csbysj202026 分钟前
Perl 数组
开发语言
雾岛听蓝28 分钟前
C++ vector:从使用到底层核心剖析
开发语言·c++
bugcome_com30 分钟前
深入解析 C# 中 const 与 readonly 的核心区别
c#