C# 创建高精度定时器的示例
背景
我们知道在.NETFramework中存在四种常用的定时器,他们分别是:
1 两个是通用的多线程定时器:
- System.Threading.Timer
- System.Timers.Timer
2 两个是专用的单线程定时器
- System.Windows.Forms.Timer (WindowsForms的定时器)
- System.Windows.Threading.DispatcherTimer (WPF的定时器)
通常他们的精度只能维持在10-20ms之间,这个和操作系统相关,所以我们在很多场景下面这个是不能够达到我们精度的要求的,如果要实现这一需求我们该怎么办,当然也有很多办法,今天主要介绍一种Stopwatch来实现的方式,网上有很多采用Win32Dll的API这个当然是可以的,这篇文章的重点不是去讨论这个,关于使用Win32API的方式可以参考这里。
实现
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Diagnostics;
usingSystem.Linq;
usingSystem.Runtime.InteropServices;
usingSystem.Text;
namespacePangea.Common.Utility
{
///
///.NetStopwatch对高精度定时器作了很好的包装
///DeviceTimer内部采用Stopwatch类实现高精度定时操作
///
publicsealedclassDeviceTimer
{
#ifUSE_CPU_COUNTING
//引入高性能计数器API,通过对CPU计数完成计时
[DllImport("Kernel32.dll")]
privatestaticexternboolQueryPerformanceCounter(outlonglpPerformanceCount);
//获取当前CPU的工作频率
[DllImport("Kernel32.dll")]
privatestaticexternboolQueryPerformanceFrequency(outlonglpFrequency);
#else
///
///获取TickCount64计数
///
///
//[DllImport("kernel32.dll")]
//publicstaticexternlongGetTickCount64();
#endif
privateenumDeviceTimerState
{
TM_ST_IDLE=0,
TM_ST_BUSY=1,
TM_ST_TIMEOUT=2,
}
///
///Stopwatchobject
///
Stopwatch_stopWatch=newStopwatch();
///
///定时器内部状态
///
DeviceTimerState_state;
///
///定时器开始计时时刻的相对时间点
///
long_startTime;
///
///定时器超时时刻的相对时间点
///
long_timeOut;
#ifUSE_CPU_COUNTING
///
///CPU运行的时钟频率
///
double_freq;
#endif
///
///定时时间(单位:ms)
///
double_duration;
///
///classconstructure
///
publicDeviceTimer()
{
#ifUSE_CPU_COUNTING
longfreq;
if(QueryPerformanceFrequency(outfreq)==false)
thrownewException("本计算机不支持高性能计数器");
//得到每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;
}
///
///内部调用:设置定时器当前状态
///
///
privatevoidSetState(DeviceTimerStatestate)
{
_state=state;
}
///
///内部调用:返回定时器当前状态
///
///
privateDeviceTimerStateGetState()
{
return_state;
}
///
///定时器开始计时到现在已流逝的时间(单位:毫秒)
///
///
publicdoubleGetElapseTime()
{
longcurCount;
#ifUSE_CPU_COUNTING
QueryPerformanceCounter(outcurCount);
return(double)(curCount-_startTime)/(double)_freq;
#else
curCount=_stopWatch.ElapsedMilliseconds;
returncurCount-_startTime;
#endif
}
///
///获取定时总时间
///
///
publicdoubleGetTotalTime()
{
return_duration;
}
///
///停止计时器计时
///
publicvoidStop()
{
SetState(DeviceTimerState.TM_ST_IDLE);
#ifUSE_CPU_COUNTING
QueryPerformanceCounter(out_startTime);
#else
_startTime=_stopWatch.ElapsedMilliseconds;
#endif
_timeOut=_startTime;
_duration=0;
}
///
///启动定时器
///
///定时时间(单位:毫秒)
publicvoidStart(doubledelay_ms)
{
#ifUSE_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;
}
///
///重新开始定时器
///开始的计时时间以上一次Start的时间为准
///
///定时时间(单位:毫秒)
publicvoidRestart(doubledelay_ms)
{
#ifUSE_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;
}
///
///返回定时器是否超时
///
///
publicboolIsTimeout()
{
if(_state==DeviceTimerState.TM_ST_IDLE)
{
//System.Diagnostics.Debug.WriteLine("Warning:Misuageofthedevicetimer.Youmuststartitfirstbeforeyoucanuseit.");
//System.Diagnostics.Debug.Assert(false,"Warning:Misuageofthedevicetimer.Youmuststartitfirstbeforeyoucanuseit.");
}
longcurCount;
#ifUSE_CPU_COUNTING
QueryPerformanceCounter(outcurCount);
#else
curCount=_stopWatch.ElapsedMilliseconds;
#endif
if(_state==DeviceTimerState.TM_ST_BUSY&&(curCount>=_timeOut))
{
SetState(DeviceTimerState.TM_ST_TIMEOUT);
returntrue;
}
elseif(_state==DeviceTimerState.TM_ST_TIMEOUT)
{
returntrue;
}
returnfalse;
}
///
///定时器是否在工作中
///
///
publicboolIsIdle()
{
return(_state==DeviceTimerState.TM_ST_IDLE);
}
}
}
这个里面我们在DeviceTimer中定义了一个私有的_stopWatch对象并且在构造函数中就启动了这个Stopwatch,所以我们在使用的时候是通过先创建一个DeveiceTimer的对象然后我们再调用内部的Start方法,当然在调用这个方法的时候我们需要传入一个定时时间,然后不断检测IsTimeout方法看是否到达定时时间,从而达到类似于定时时间到的效果,另外GetElapseTime()方法能够获取从调用Start方法开始到现在的时间,另外我们还在其中定义了几个枚举值用来表示当前DeviceTimer的状态用于做一些状态的校验,具体数值如下。
privateenumDeviceTimerState
{
TM_ST_IDLE=0,
TM_ST_BUSY=1,
TM_ST_TIMEOUT=2,
}
这里还有最后一个问题就是循环调用的问题,这个其实也是非常简单就在一个While循环中不断进行调用,当然下面的代码可以有很多内容供我们去发挥的,这个可以根据自己的需要进行修改。
usingSystem;
usingSystem.Threading.Tasks;
namespaceDeviceTimerConsoleApp
{
classProgram
{
privatestaticboolflag=true;
staticvoidMain(string[]args)
{
Task.Factory.StartNew(()=>
{
vardeviceTimer=newDeviceTimer();
deviceTimer.Start(5);
while(flag)
{
if(deviceTimer.IsTimeout())
{
Console.WriteLine($"定时时间已到,距离开始执行已过去:{deviceTimer.GetElapseTime()}ms");
deviceTimer.Start(5);
}
}
});
Console.ReadKey();
}
}
}
我们来看看定时器的效果
以上就是C#创建高精度定时器的示例的详细内容,更多关于C#创建高精度定时器的资料请关注毛票票其它相关文章!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。