C# 创建高精度定时器的示例

这篇文章主要介绍了C# 创建高精度定时器的示例,帮助大家更好的理解和学习使用c#,感兴趣的朋友可以了解下

背景

 我们知道在.NET Framework中存在四种常用的定时器,他们分别是:

1 两个是通用的多线程定时器:

  • System.Threading.Timer
  • System.Timers.Timer

2 两个是专用的单线程定时器

  • System.Windows.Forms.Timer (Windows Forms 的定时器)
  • System.Windows.Threading.DispatcherTimer (WPF 的定时器)

通常他们的精度只能维持在10-20ms之间,这个和操作系统相关,所以我们在很多场景下面这个是不能够达到我们精度的要求的,如果要实现这一需求我们该怎么办,当然也有很多办法,今天主要介绍一种Stopwatch来实现的方式,网上有很多采用Win32 Dll的API这个当然是可以的,这篇文章的重点不是去讨论这个,关于使用Win32 API的方式可以参考这里。

实现


using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
 
namespace Pangea.Common.Utility
{
    /// <summary>
    /// .Net Stopwatch对高精度定时器作了很好的包装
    /// DeviceTimer内部采用Stopwatch类实现高精度定时操作
    /// </summary>
    public sealed class DeviceTimer
    {
#if USE_CPU_COUNTING
        //引入高性能计数器API,通过对CPU计数完成计时
        [DllImport("Kernel32.dll")]
        private static extern bool QueryPerformanceCounter(out long lpPerformanceCount);
 
        //获取当前CPU的工作频率
        [DllImport("Kernel32.dll")]
        private static extern bool QueryPerformanceFrequency(out long lpFrequency);
#else
        /// <summary>
        /// 获取TickCount64计数
        /// </summary>
        /// <returns></returns>
        //[DllImport("kernel32.dll")]
        //public static extern long GetTickCount64();
#endif
        private enum DeviceTimerState
        {
            TM_ST_IDLE = 0,
            TM_ST_BUSY = 1,
            TM_ST_TIMEOUT = 2,
        }
 
        /// <summary>
        /// Stopwatch object
        /// </summary>
        Stopwatch _stopWatch = new Stopwatch();
 
        /// <summary>
        /// 定时器内部状态
        /// </summary>
        DeviceTimerState _state;
 
        /// <summary>
        /// 定时器开始计时时刻的相对时间点
        /// </summary>
        long _startTime;
 
        /// <summary>
        /// 定时器超时时刻的相对时间点
        /// </summary>
        long _timeOut;
 
#if USE_CPU_COUNTING
 
        /// <summary>
        /// CPU运行的时钟频率
        /// </summary>
        double _freq;
#endif
 
        /// <summary>
        /// 定时时间(单位:ms)
        /// </summary>
        double _duration;
 
        /// <summary>
        /// class constructure
        /// </summary>
        public DeviceTimer()
        {
#if USE_CPU_COUNTING
            long freq;
            if (QueryPerformanceFrequency(out freq) == false)
                throw new Exception("本计算机不支持高性能计数器");
            //得到每1ms的CPU计时TickCount数目
            _freq = (double)freq / 1000.0;
            QueryPerformanceCounter(out _startTime);
#else
            _stopWatch.Start();
            _startTime = 0;
#endif
            SetState(DeviceTimerState.TM_ST_IDLE);
            _timeOut = _startTime;
            _duration = 0;
        }
 
        /// <summary>
        /// 内部调用:设置定时器当前状态
        /// </summary>
        /// <param name="state"></param>
        private void SetState(DeviceTimerState state)
        {
            _state = state;
        }
 
        /// <summary>
        /// 内部调用:返回定时器当前状态
        /// </summary>
        /// <returns></returns>
        private DeviceTimerState GetState()
        {
            return _state;
        }
 
        /// <summary>
        /// 定时器开始计时到现在已流逝的时间(单位:毫秒)
        /// </summary>
        /// <returns></returns>
        public double GetElapseTime()
        {
            long curCount;
#if USE_CPU_COUNTING
            QueryPerformanceCounter(out curCount);
            return (double)(curCount - _startTime) / (double)_freq;
#else
            curCount = _stopWatch.ElapsedMilliseconds;
            return curCount - _startTime;
#endif
        }
 
        /// <summary>
        /// 获取定时总时间
        /// </summary>
        /// <returns></returns>
        public double GetTotalTime()
        {
            return _duration;
        }
 
        /// <summary>
        /// 停止计时器计时
        /// </summary>
        public void Stop()
        {
            SetState(DeviceTimerState.TM_ST_IDLE);
#if USE_CPU_COUNTING
            QueryPerformanceCounter(out _startTime);
#else
            _startTime = _stopWatch.ElapsedMilliseconds;
#endif
            _timeOut = _startTime;
            _duration = 0;
        }
 
        /// <summary>
        /// 启动定时器
        /// </summary>
        /// <param name="delay_ms">定时时间(单位:毫秒)</param>
        public void Start(double delay_ms)
        {
#if USE_CPU_COUNTING
            QueryPerformanceCounter(out _startTime);
            _timeOut = Convert.ToInt64(_startTime + delay_ms * _freq);
#else
            _startTime = _stopWatch.ElapsedMilliseconds;
            _timeOut = Convert.ToInt64(_startTime + delay_ms);
#endif
            SetState(DeviceTimerState.TM_ST_BUSY);
            _duration = delay_ms;
        }
 
        /// <summary>
        /// 重新开始定时器
        /// 开始的计时时间以上一次Start的时间为准
        /// </summary>
        /// <param name="delay_ms">定时时间(单位:毫秒)</param>
        public void Restart(double delay_ms)
        {
#if USE_CPU_COUNTING
            _timeOut = Convert.ToInt64(_startTime + delay_ms * _freq);
#else
            _timeOut = Convert.ToInt64(_startTime + delay_ms);
#endif
            SetState(DeviceTimerState.TM_ST_BUSY);
            _duration = delay_ms;
        }
 
        /// <summary>
        /// 返回定时器是否超时
        /// </summary>
        /// <returns></returns>
        public bool IsTimeout()
        {
            if (_state == DeviceTimerState.TM_ST_IDLE)
            {
                //System.Diagnostics.Debug.WriteLine("Warning: Misuage of the device timer. You must start it first before you can use it.");
                //System.Diagnostics.Debug.Assert(false, "Warning: Misuage of the device timer. You must start it first before you can use it.");
            }
            long curCount;
#if USE_CPU_COUNTING
            QueryPerformanceCounter(out curCount);
#else
            curCount = _stopWatch.ElapsedMilliseconds;
#endif
            if (_state == DeviceTimerState.TM_ST_BUSY && (curCount >= _timeOut))
            {
                SetState(DeviceTimerState.TM_ST_TIMEOUT);
                return true;
            }
            else if (_state == DeviceTimerState.TM_ST_TIMEOUT)
            {
                return true;
            }
            return false;
        }
 
        /// <summary>
        /// 定时器是否在工作中
        /// </summary>
        /// <returns></returns>
        public bool IsIdle()
        {
            return (_state == DeviceTimerState.TM_ST_IDLE);
        }
    }
}

  这个里面我们在DeviceTimer中定义了一个私有的_stopWatch 对象并且在构造函数中就启动了这个Stopwatch,所以我们在使用的时候是通过先创建一个DeveiceTimer的对象然后我们再调用内部的Start方法,当然在调用这个方法的时候我们需要传入一个定时时间,然后不断检测IsTimeout方法看是否到达定时时间,从而达到类似于定时时间到的效果,另外GetElapseTime()方法能够获取从调用Start方法开始到现在的时间,另外我们还在其中定义了几个枚举值用来表示当前DeviceTimer的状态用于做一些状态的校验,具体数值如下。


private enum DeviceTimerState
{
    TM_ST_IDLE = 0,
    TM_ST_BUSY = 1,
    TM_ST_TIMEOUT = 2,
}

  这里还有最后一个问题就是循环调用的问题,这个其实也是非常简单就在一个While循环中不断进行调用,当然下面的代码可以有很多内容供我们去发挥的,这个可以根据自己的需要进行修改。


using System;
using System.Threading.Tasks;
 
namespace DeviceTimerConsoleApp
{
    class Program
    {
        private static bool flag = true;
        static void Main(string[] args)
        {
            Task.Factory.StartNew(() =>
            {
                var deviceTimer = new DeviceTimer();
                deviceTimer.Start(5);
 
                while (flag)
                {
                    if (deviceTimer.IsTimeout())
                    {
                        Console.WriteLine($"定时时间已到,距离开始执行已过去:{deviceTimer.GetElapseTime()}ms");
 
                        deviceTimer.Start(5);
                    }
                }
            });
            Console.ReadKey();
        }
    }
     
}

  我们来看看定时器的效果

以上就是C# 创建高精度定时器的示例的详细内容,更多关于C# 创建高精度定时器的资料请关注得得之家其它相关文章!

本文标题为:C# 创建高精度定时器的示例