Timer计时不准确的问题及解决方法
在项目中,需要每隔20ms发送一个RTP数据包。一开始使用的是System.Windows.Forms下的Timer类,但是发现明显延迟了。用StopWatch测了一下,发现它的触发间隔居然不是20ms,而是在31ms左右摇摆。换了System.Threading下的Timer和System.Timers下和Timer也不行,一样的问题。
为什么会这样呢?在网上发现了一段非常具有启发性的话,它解释了原因并给出了解决的办法:
目前,Windows软件一般使用Timer定时器进行定时。Timer定时器是由应用程序响应定时消息WM_TIMER实现定时。Timer定时器是IBM PC硬件和ROM BIOS构造的定时器的简单扩充。PC的ROM初始化8253定时器来产生硬件中断08H,而08H中断的频率为18.2Hz,即至少每隔54.925 ms中断一次。此外,这个定时消息的优先权太低,只有在除WM_PAINT外的所有消息被处理完后,才能得到处理。
多媒体定时器也是利用系统定时器工作的,但它的工作机理和普通定时器有所不同。首先,多媒体定时器可以按精度要求设置8253的T/C0通道的计数初值,使定时器不存在54.945ms的限制;其次,多媒体定时器不依赖于消息机制,而是用函数产生一个独立的线程,在一定的中断次数到达后,直接调用预先设置好的回调函数进行处理,不必等到应用程序的消息队列为空,从而切实保障了定时中断得到实时响应,使其定时精度可达1ms。
这段话中的多媒体定时器被放在了winmm.dll中。要使用这个定时器,可以通过调用timeSetEvent和timeKillEvent函数来实现。为了便于使用,参照网上的一些资料,对这两个方法进行了封装。现跟大家分享一下。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Threading;
using System.ComponentModel; public sealed class MillisecondTimer : IComponent, IDisposable
{ //***************************************************** 字 段 *******************************************************************
private static TimerCaps caps;
private int interval;
private bool isRunning;
private int resolution;
private TimerCallback timerCallback;
private int timerID; //***************************************************** 属 性 *******************************************************************
/// <summary>
///
/// </summary>
public int Interval
{
get
{
return this.interval;
}
set
{
if( ( value < caps.periodMin ) || ( value > caps.periodMax ) )
{
throw new Exception( "超出计时范围!" );
}
this.interval = value;
}
} /// <summary>
///
/// </summary>
public bool IsRunning
{
get
{
return this.isRunning;
}
} /// <summary>
///
/// </summary>
public ISite Site
{
set;
get;
} //***************************************************** 事 件 ******************************************************************* public event EventHandler Disposed; // 这个事件实现了IComponet接口
public event EventHandler Tick; //*************************************************** 构造函数和释构函数 ****************************************************************** static MillisecondTimer()
{
timeGetDevCaps( ref caps, Marshal.SizeOf( caps ) );
} public MillisecondTimer()
{
this.interval = caps.periodMin; //
this.resolution = caps.periodMin; // this.isRunning = false;
this.timerCallback = new TimerCallback( this.TimerEventCallback ); } public MillisecondTimer( IContainer container )
: this()
{
container.Add( this );
} ~MillisecondTimer()
{
timeKillEvent( this.timerID );
} //***************************************************** 方 法 ******************************************************************* /// <summary>
///
/// </summary>
public void Start()
{
if( !this.isRunning )
{
this.timerID = timeSetEvent( this.interval, this.resolution, this.timerCallback, , ); // 间隔性地运行 if( this.timerID == )
{
throw new Exception( "无法启动计时器" );
}
this.isRunning = true;
}
} /// <summary>
///
/// </summary>
public void Stop()
{
if( this.isRunning )
{
timeKillEvent( this.timerID );
this.isRunning = false;
}
} /// <summary>
/// 实现IDisposable接口
/// </summary>
public void Dispose()
{
timeKillEvent( this.timerID );
GC.SuppressFinalize( this );
EventHandler disposed = this.Disposed;
if( disposed != null )
{
disposed( this, EventArgs.Empty );
}
} //*************************************************** 内部函数 ******************************************************************
[DllImport( "winmm.dll" )]
private static extern int timeSetEvent( int delay, int resolution, TimerCallback callback, int user, int mode ); [DllImport( "winmm.dll" )]
private static extern int timeKillEvent( int id ); [DllImport( "winmm.dll" )]
private static extern int timeGetDevCaps( ref TimerCaps caps, int sizeOfTimerCaps );
// The timeGetDevCaps function queries the timer device to determine its resolution. private void TimerEventCallback( int id, int msg, int user, int param1, int param2 )
{
if( this.Tick != null )
{
this.Tick( this, null ); // 引发事件
}
} //*************************************************** 内部类型 ****************************************************************** private delegate void TimerCallback( int id, int msg, int user, int param1, int param2 ); // timeSetEvent所对应的回调函数的签名 /// <summary>
/// 定时器的分辨率(resolution)。单位是ms,毫秒?
/// </summary>
[StructLayout( LayoutKind.Sequential )]
private struct TimerCaps
{
public int periodMin;
public int periodMax;
} }
调用方法:
MillisecondTimer timer1;
private void button1_Click( object sender, EventArgs e )
{
timer1 = new MillisecondTimer();
timer1.Interval = ;
timer1.Tick += new EventHandler( timer1_Tick );
timer1.Start();
}
int i;
void timer1_Tick( object sender, EventArgs e )
{
Console.WriteLine( i++ );
}
private void button2_Click( object sender, EventArgs e )
{
timer1.Stop();
timer1.Dispose();
}
参考:
Timer计时不准确的问题及解决方法的更多相关文章
- Timer计时不准确的解决方案 每次都重新调整,修正误差
http://stackoverflow.com/questions/29722838/system-timers-timer-steadily-increasing-the-interval 需要在 ...
- php浮点数计算比较及取整不准确解决方法
原文:php浮点数计算比较及取整不准确解决方法 php有意思的现象,应该是很多编程语言都会有这样的现象.这个是因为计算机的本身对浮点数识别的问题..... $f = 0.58; var_dump(in ...
- 阿里云 ECS centos java timer进程异常/混乱......的解决方法
之前就知道timer进程长久运行容易出问题,所以一直对timer进行了很长一段时间的日志监控和数据库记录,大概观察了几个月,没发现过问题....然后就没管理了,数据库记录也没做了,昨天这问题就来了,t ...
- ExtJs4.2中Tab选项卡的右击关闭其它和关闭当前功能不准确的解决方法
一.ExtJs4.2中Tab选项卡的右击关闭其它和关闭当前功能不准确的解决方法 二.找到ux目录下的TabCloseMenu.js文件,将内容替换成下面代码. 三.代码: /** * Plugin f ...
- 小程序 RecorderManager计时不准确问题
官方文档:RecorderManager 录音管理器,内部实现计时不准确.有以下俩个问题: 点击暂停继续,当录音结束时,stop返回的时间包含了暂停的那一段时间. 正常录音,录音文件的时长有概率少个1 ...
- window.onresize 多次触发的解决方法
用了window.onresize但是发现每次 onresize 后页面中状态总是不对,下面与大家分享下onresize 事件多次触发的解决方法. 之前做一个扩展,需要在改变窗口大小的时候保证页面显示 ...
- MVVM框架从WPF移植到UWP遇到的问题和解决方法
MVVM框架从WPF移植到UWP遇到的问题和解决方法 0x00 起因 这几天开始学习UWP了,之前有WPF经验,所以总体感觉还可以,看了一些基础概念和主题,写了几个测试程序,突然想起来了前一段时间在W ...
- Sublime Text 无法使用Package Control的解决方法 以及 常用的插件安装过程
大概一个月之前给 Macbook air 装 Sublime Text 3 的时候,遇到过这个问题,当时解决了,现在回想,感觉忘的七七八八了,赶紧趁着还没有全忘光的时候记下来,当时的过程记得不一定准确 ...
- android手机出现sqlite3 not found的解决方法
解决方法如下: 1.如果/system目录为不可读写的,需要挂载为读写: C:\Users\easteq>adb shell root@android:/ # mount -o remount, ...
随机推荐
- [转]Docker容器可视化监控中心搭建
[原文链接]https://www.jianshu.com/p/9e47ffaf5e31?hmsr=toutiao.io&utm_medium=toutiao.io&utm_sourc ...
- Java获取数据库表 字段 存储的部分数据
在浏览器页面,选中图片(可多选) >单击删除按钮. 重点是, 本数据库表TabHeBeiTianQi中 存在 同一id,对应的picLocalPath字段 存储了多张图片,图片地址用 逗号 ...
- [cb]ScriptableWizard 创建向导
需求 方便策划一步一步的创建Actor 思路分析 Unity的Editor中提供创建向导的功能,ScriptableWizard 代码实现 创建一个WizardCreateActor继承自Script ...
- Matplotlib:tick_params参数设置
1.tick_params语法 参数:axis : {‘x’, ‘y’, ‘both’} Axis on which to operate; default is ‘both’.reset : boo ...
- RESTframework简介
什么是RESTful? RESTful是一种开发理念,REST是Roy Thomas Fileding在他博文提出的.REST特点;url简洁,将参数通过url传递到服务器,简单就是说URL定位资源, ...
- 为PHP7安装Windows Server 2012 R2过程记录
因为要安装php-7.0.6-Win32-VC14-x64,需要先安装vcredist2015_x64_14.0.23026.0. 之前安装了Windows Server 2012 R2后,一直无法成 ...
- Mac OS X 下优化 Terminal,一篇就够了!
先上最终效果图: 目录 目录 1. 相关工具介绍 2. 配置总览 3. 安装步骤 3.1. 安装 iTerm2 3.2. 安装XCode's Command line tools 3.3. 检查 zs ...
- java按行和列进行输出数据
package debug; public class Demo9 { public static void main(String[] args) { //输出4行5列星星 //外循环控制行数 // ...
- 公式编辑器MathType基本使用方法总结----应付本科毕业论文完全没问题啦^_^
本人计算数学专业毕业,写毕业论文和外文翻译的时候会遇到大量公式需要编辑,而且学校一般都要求用word.但是Word自带的公式编辑器只支持一种字体,当公式中涉及到特殊字体就不太方便了.如果用Latex来 ...
- JavaScipt中的Math.ceil() 、Math.floor() 、Math.round()、Math.pow() 三个函数的理解
以前一直会三个函数的使用产生混淆,现在通过对三个函数的原型定义的理解,其实很容易记住三个函数. 现在做一个总结: 1. Math.ceil()用作向上取整. 2. Math.floor()用作向下取整 ...