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# 創建高精度定時器的資料請關註WalkonNet其它相關文章!

推薦閱讀: