亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

C# 創(chuàng)建高精度定時(shí)器的示例

 更新時(shí)間:2021年02月27日 15:31:07   作者:Hello——尋夢(mèng)者!  
這篇文章主要介紹了C# 創(chuàng)建高精度定時(shí)器的示例,幫助大家更好的理解和學(xué)習(xí)使用c#,感興趣的朋友可以了解下

背景

 我們知道在.NET Framework中存在四種常用的定時(shí)器,他們分別是:

1 兩個(gè)是通用的多線程定時(shí)器:

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

2 兩個(gè)是專(zhuān)用的單線程定時(shí)器

  • System.Windows.Forms.Timer (Windows Forms 的定時(shí)器)
  • System.Windows.Threading.DispatcherTimer (WPF 的定時(shí)器)

通常他們的精度只能維持在10-20ms之間,這個(gè)和操作系統(tǒng)相關(guān),所以我們?cè)诤芏鄨?chǎng)景下面這個(gè)是不能夠達(dá)到我們精度的要求的,如果要實(shí)現(xiàn)這一需求我們?cè)撛趺崔k,當(dāng)然也有很多辦法,今天主要介紹一種Stopwatch來(lái)實(shí)現(xiàn)的方式,網(wǎng)上有很多采用Win32 Dll的API這個(gè)當(dāng)然是可以的,這篇文章的重點(diǎn)不是去討論這個(gè),關(guān)于使用Win32 API的方式可以參考這里。

實(shí)現(xiàn)

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對(duì)高精度定時(shí)器作了很好的包裝
    /// DeviceTimer內(nèi)部采用Stopwatch類(lèi)實(shí)現(xiàn)高精度定時(shí)操作
    /// </summary>
    public sealed class DeviceTimer
    {
#if USE_CPU_COUNTING
        //引入高性能計(jì)數(shù)器API,通過(guò)對(duì)CPU計(jì)數(shù)完成計(jì)時(shí)
        [DllImport("Kernel32.dll")]
        private static extern bool QueryPerformanceCounter(out long lpPerformanceCount);
 
        //獲取當(dāng)前CPU的工作頻率
        [DllImport("Kernel32.dll")]
        private static extern bool QueryPerformanceFrequency(out long lpFrequency);
#else
        /// <summary>
        /// 獲取TickCount64計(jì)數(shù)
        /// </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>
        /// 定時(shí)器內(nèi)部狀態(tài)
        /// </summary>
        DeviceTimerState _state;
 
        /// <summary>
        /// 定時(shí)器開(kāi)始計(jì)時(shí)時(shí)刻的相對(duì)時(shí)間點(diǎn)
        /// </summary>
        long _startTime;
 
        /// <summary>
        /// 定時(shí)器超時(shí)時(shí)刻的相對(duì)時(shí)間點(diǎn)
        /// </summary>
        long _timeOut;
 
#if USE_CPU_COUNTING
 
        /// <summary>
        /// CPU運(yùn)行的時(shí)鐘頻率
        /// </summary>
        double _freq;
#endif
 
        /// <summary>
        /// 定時(shí)時(shí)間(單位:ms)
        /// </summary>
        double _duration;
 
        /// <summary>
        /// class constructure
        /// </summary>
        public DeviceTimer()
        {
#if USE_CPU_COUNTING
            long freq;
            if (QueryPerformanceFrequency(out freq) == false)
                throw new Exception("本計(jì)算機(jī)不支持高性能計(jì)數(shù)器");
            //得到每1ms的CPU計(jì)時(shí)TickCount數(shù)目
            _freq = (double)freq / 1000.0;
            QueryPerformanceCounter(out _startTime);
#else
            _stopWatch.Start();
            _startTime = 0;
#endif
            SetState(DeviceTimerState.TM_ST_IDLE);
            _timeOut = _startTime;
            _duration = 0;
        }
 
        /// <summary>
        /// 內(nèi)部調(diào)用:設(shè)置定時(shí)器當(dāng)前狀態(tài)
        /// </summary>
        /// <param name="state"></param>
        private void SetState(DeviceTimerState state)
        {
            _state = state;
        }
 
        /// <summary>
        /// 內(nèi)部調(diào)用:返回定時(shí)器當(dāng)前狀態(tài)
        /// </summary>
        /// <returns></returns>
        private DeviceTimerState GetState()
        {
            return _state;
        }
 
        /// <summary>
        /// 定時(shí)器開(kāi)始計(jì)時(shí)到現(xiàn)在已流逝的時(shí)間(單位:毫秒)
        /// </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>
        /// 獲取定時(shí)總時(shí)間
        /// </summary>
        /// <returns></returns>
        public double GetTotalTime()
        {
            return _duration;
        }
 
        /// <summary>
        /// 停止計(jì)時(shí)器計(jì)時(shí)
        /// </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>
        /// 啟動(dòng)定時(shí)器
        /// </summary>
        /// <param name="delay_ms">定時(shí)時(shí)間(單位:毫秒)</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>
        /// 重新開(kāi)始定時(shí)器
        /// 開(kāi)始的計(jì)時(shí)時(shí)間以上一次Start的時(shí)間為準(zhǔn)
        /// </summary>
        /// <param name="delay_ms">定時(shí)時(shí)間(單位:毫秒)</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>
        /// 返回定時(shí)器是否超時(shí)
        /// </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>
        /// 定時(shí)器是否在工作中
        /// </summary>
        /// <returns></returns>
        public bool IsIdle()
        {
            return (_state == DeviceTimerState.TM_ST_IDLE);
        }
    }
}

  這個(gè)里面我們?cè)贒eviceTimer中定義了一個(gè)私有的_stopWatch 對(duì)象并且在構(gòu)造函數(shù)中就啟動(dòng)了這個(gè)Stopwatch,所以我們?cè)谑褂玫臅r(shí)候是通過(guò)先創(chuàng)建一個(gè)DeveiceTimer的對(duì)象然后我們?cè)僬{(diào)用內(nèi)部的Start方法,當(dāng)然在調(diào)用這個(gè)方法的時(shí)候我們需要傳入一個(gè)定時(shí)時(shí)間,然后不斷檢測(cè)IsTimeout方法看是否到達(dá)定時(shí)時(shí)間,從而達(dá)到類(lèi)似于定時(shí)時(shí)間到的效果,另外GetElapseTime()方法能夠獲取從調(diào)用Start方法開(kāi)始到現(xiàn)在的時(shí)間,另外我們還在其中定義了幾個(gè)枚舉值用來(lái)表示當(dāng)前DeviceTimer的狀態(tài)用于做一些狀態(tài)的校驗(yàn),具體數(shù)值如下。

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

  這里還有最后一個(gè)問(wèn)題就是循環(huán)調(diào)用的問(wèn)題,這個(gè)其實(shí)也是非常簡(jiǎn)單就在一個(gè)While循環(huán)中不斷進(jìn)行調(diào)用,當(dāng)然下面的代碼可以有很多內(nèi)容供我們?nèi)グl(fā)揮的,這個(gè)可以根據(jù)自己的需要進(jìn)行修改。

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($"定時(shí)時(shí)間已到,距離開(kāi)始執(zhí)行已過(guò)去:{deviceTimer.GetElapseTime()}ms");
 
                        deviceTimer.Start(5);
                    }
                }
            });
            Console.ReadKey();
        }
    }
     
}

  我們來(lái)看看定時(shí)器的效果

以上就是C# 創(chuàng)建高精度定時(shí)器的示例的詳細(xì)內(nèi)容,更多關(guān)于C# 創(chuàng)建高精度定時(shí)器的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • 深入了解C#多線程安全

    深入了解C#多線程安全

    使用多線程無(wú)法避免的一個(gè)問(wèn)題就是多線程安全。那什么是多線程安全?如何解決多線程安全?本文將通過(guò)一些簡(jiǎn)單的例子為大家詳細(xì)介紹一下多線程相關(guān)的問(wèn)題,感興趣的可以了解一下
    2021-12-12
  • C#5.0中的異步編程關(guān)鍵字async和await

    C#5.0中的異步編程關(guān)鍵字async和await

    這篇文章介紹了C#5.0中的異步編程關(guān)鍵字async和await,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-06-06
  • C#使用FluentScheduler實(shí)現(xiàn)觸發(fā)定時(shí)任務(wù)

    C#使用FluentScheduler實(shí)現(xiàn)觸發(fā)定時(shí)任務(wù)

    FluentScheduler是.Net平臺(tái)下的一個(gè)自動(dòng)任務(wù)調(diào)度組件,這篇文章主要為大家詳細(xì)介紹了C#如何使用FluentScheduler實(shí)現(xiàn)觸發(fā)定時(shí)任務(wù),感興趣的小伙伴可以了解下
    2023-12-12
  • C#編程獲取實(shí)體類(lèi)屬性名和值的方法示例

    C#編程獲取實(shí)體類(lèi)屬性名和值的方法示例

    這篇文章主要介紹了C#編程獲取實(shí)體類(lèi)屬性名和值的方法,涉及C#實(shí)體類(lèi)的定義、實(shí)例化、遍歷等相關(guān)操作技巧,需要的朋友可以參考下
    2017-04-04
  • C#?StartsWith?字符串的實(shí)例方法解析

    C#?StartsWith?字符串的實(shí)例方法解析

    這篇文章主要介紹了C#?StartsWith?字符串的實(shí)例方法,StartsWith?方法對(duì)于需要檢查字符串的前綴是否匹配特定模式的情況非常有用,你可以根據(jù)返回的布爾值,根據(jù)需要執(zhí)行相應(yīng)的邏輯操作,需要的朋友可以參考下
    2024-03-03
  • C#實(shí)現(xiàn)XML序列化與反序列化

    C#實(shí)現(xiàn)XML序列化與反序列化

    這篇文章介紹了C#實(shí)現(xiàn)XML序列化與反序列化的方法,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-06-06
  • C# 文件下載之?dāng)帱c(diǎn)續(xù)傳實(shí)現(xiàn)代碼

    C# 文件下載之?dāng)帱c(diǎn)續(xù)傳實(shí)現(xiàn)代碼

    本篇文章主要介紹了C# 文件下載之?dāng)帱c(diǎn)續(xù)傳實(shí)現(xiàn)代碼,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2017-01-01
  • C#開(kāi)發(fā)Winform控件之打開(kāi)文件對(duì)話框OpenFileDialog類(lèi)

    C#開(kāi)發(fā)Winform控件之打開(kāi)文件對(duì)話框OpenFileDialog類(lèi)

    這篇文章介紹了C#開(kāi)發(fā)Winform控件之打開(kāi)文件對(duì)話框OpenFileDialog類(lèi),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2022-02-02
  • C# 中string.split用法詳解

    C# 中string.split用法詳解

    本文給大家分享了C# 中string.split用法的相關(guān)知識(shí),非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友參考下吧
    2017-06-06
  • 在winform中嵌入第三方軟件窗體的實(shí)踐分享

    在winform中嵌入第三方軟件窗體的實(shí)踐分享

    這篇文章主要介紹了在winform中如何嵌入第三方軟件窗體的實(shí)踐分享,文中通過(guò)代碼示例和圖文給大家介紹的非常詳細(xì),具有一定參考價(jià)值,需要的朋友可以參考下
    2024-03-03

最新評(píng)論