C# 创建高精度定时器的示例
作者:Hello——寻梦者! 发布时间:2023-03-09 12:35:58
背景
我们知道在.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();
}
}
}
我们来看看定时器的效果
来源:https://www.cnblogs.com/seekdream/p/13870933.html
猜你喜欢
- RestTemplate未设置超时时间,导致RabbitMQ队列大量堆积,消费者假死,不进行消费,类似线程堵塞。排查:从日志排查问题,在从进
- 1、lock是可中断锁,而synchronized 不是可中断锁线程A和B都要获取对象O的锁定,假设A获取了对象O锁,B将等待A释放对O的锁
- Spring boot + Spring data jpa + Thymeleaf批量插入 + POI读取 + 文件上传pom.xml:&l
- 在微信公众号里面需要上传头像,时间比较紧,调用学习jssdk并使用 来不及 就用了input1、使用input:file标签, 去调用系统默
- static关键字static关键词与对象无关。static关键字主要修饰四个部分的内容这里我们主要介绍static修饰属性和修饰方法。1.
- public String[] split(String regex) 默认limit为0public String[] split(Str
- 写在前面:接下来很长一段时间的文章主要会记录一些项目中实际遇到的问题及对应的解决方案,在相应代码分析时会直指问题所在,不会将无关的流程代码贴
- 本文实例讲述了C#创建临时文件的方法。分享给大家供大家参考。具体分析如下:C#可以通过Path.GetTempFileName获得一个临时文
- 介绍本篇主要介绍kafka的 * 和序列化器,序列化器是和数据在网络中的传输有关,数据在网络中的传输为字节流,所以生产者在发送时需要将其序列
- java spring 通过注解方式创建对象首先 我们要搞清楚一个基础概念什么是注解?注解可以说是代码里的一些特殊标记。格式是 @() 里面
- 二维数组遍历:思想:1.先将二维数组中所有的元素拿到2.再将二维数组中每个元素进行遍历,相当于就是在遍历一个一维数组第一种方法:双重for循
- [LeetCode] 205. Isomorphic Strings 同构字符串Given two strings s
- 经过几天的折腾,终于到了学习一个重量级的查询方式上,使用@Query注解,使用注解有两种方式,一种是JPQL的SQL语言方式,一种是原生SQ
- 1. 你可以讲下进程与线程的区别?为什么要用多线程?进程:进程是程序的一次执行过程,是系统运行程序的基本单位。线程:单个进程中执行中每个任务
- 本文实例讲述了C#使用oledb操作excel文件的方法。分享给大家供大家参考。具体分析如下:不管什么编程语言都会提供操作Excel文件的方
- 简介Maven为我们封装了很多构建中非常有用的操作,我们只需要执行简单的几个mvn命令即可。今天我们要讨论一下mvn命令之下的生命周期的构建
- JAVA 中Spring的@Async用法总结引言: 在Java应用中,绝大多数情况下都是通过同步的方式来实现交互处理的;但是在处理与第三方
- 一、Monkey 是什么?Monkey 就是SDK中附带的一个工具。二、Monkey 测试的目的?:该工具用于进行压力测试。 然后开发人员结
- 多说无益,贴代码:/** * 校验银行卡卡号 * * @param cardId &nbs
- 一、背景介绍在微服务都是以HTTP接口的形式暴露自身服务的,因此在调用远程服务时就必须使用HTTP客户端。我们可以使用JDK原生的URLCo