C# winform中自定义精确定时器(经测试稳定可靠)
原C#的定时器时间越长,误差越大。
在主动请求设备数据的使用,使用C#的几种自带定时器导致每天都会丢失几条数据。
经测试使用自定义的定时器可完全解决此问题。
使用方法:
MillisecondTimer _sysTimer;
_sysTimer = new MillisecondTimer();
_sysTimer.Tick += sysTimer_Tick; ;
_sysTimer.Interval = 1000; //每秒执行
_sysTimer.Start();
private void sysTimer_Tick(object sender, EventArgs e)
{
//需要定时执行的内容
}
自定义类(MillisecondTimer.cs)如下:
using System;
using System.Runtime.InteropServices;
using System.ComponentModel; namespace TEST
{
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; 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);
} public void Start()
{
if (!this.isRunning)
{
this.timerID = timeSetEvent(this.interval, this.resolution, this.timerCallback, , ); // 间隔性地运行 if (this.timerID == )
{
throw new Exception("无法启动计时器");
}
this.isRunning = true;
}
} 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;
} }
}
C# winform中自定义精确定时器(经测试稳定可靠)的更多相关文章
- Winform中自定义xml配置文件后对节点进行读取与写入
场景 Winform中自定义xml配置文件,并配置获取文件路径: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/100522648 ...
- Winform中自定义添加ZedGraph右键实现设置所有Y轴刻度的上下限
场景 Winforn中实现ZedGraph自定义添加右键菜单项(附源码下载): https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/10 ...
- Winform中自定义ZedGraph右键复制成功后的提示
场景 Winform中实现ZedGraph中曲线右键显示为中文: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/100115292 ...
- Winform中自定义xml配置文件,并配置获取文件路径
场景 在Winform程序中,需要将一些配置项存到配置文件中,这时就需要自定义xml的配置文件格式.并在一些工具类中去获取配置文件的路径并加载其内容. 关注公众号霸道的程序猿获取编程相关电子书.教程推 ...
- C# winform中自定义用户控件 然后在页面中调用用户控件的事件
下面是用户控件的代码: using System; using System.Collections.Generic; using System.ComponentModel; using Syste ...
- c#(winform)中自定义ListItem类方便ComboBox添加Item项
1.定义ListItem类 public class ListItem { private string _key = string.Empty; private string _value = st ...
- WinForm中自定义搜索框(水印、清空按钮、加载中图标)
public partial class CustomSearchBar : TextBox { private readonly Label lblwaterText = new Label(); ...
- C# Winform中自定义筛选及自带统计行的Datagridview控件
网上分享有很多种自制DGV控件,都有不小的缺陷. 没办法,按需求自己定制了一个. 一.过滤方面类似于Excel的筛选功能.支持右键菜单筛选,同时也支持在文本框输入文字按焦点列进行筛选: 二.统计行我采 ...
- Winform中对自定义xml配置文件进行Xml节点的添加与删除
场景 Winform中自定义xml配置文件后对节点进行读取与写入: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/10053213 ...
随机推荐
- 【nodejs】安装browser-sync 遇到错误提示
首先我用的是mac电脑在我执行安装browser-sync时遇到如下问题: 因为不被允许所以我只能不安装全局了: 但是又出现了如下的新问题 纠结了半个小时,终于知道为什么会出现这个问题了, node只 ...
- JSONP 详解
1.什么是JSONP ? JSONP(JSON with Padding)是一个非官方的协议,它允许在服务器端集成Script tags返回至客户端,通过javascript callback的形式实 ...
- angular路由守卫
路由守卫是指当用户满足了某些要求之后才可以离开或者进入某个页面或者场景的时候使用.比如说只有当用户填写了用户名和密码之后才可以进入首页,比如说用户离开某个页面时明月保存信息提示用户是否保存信息后再离 ...
- Django REST framework+Vue 打造生鲜超市(三)
四.xadmin后台管理 4.1.xadmin添加富文本插件 (1)xadmin/plugins文件夹下新建文件ueditor.py 代码如下: # xadmin/plugins/ueditor.py ...
- apollo1.7.1初探(一)安装apollo、创建并启动broker
Apache Apollo是一个代理服务器,是在ActiveMQ基础上发展而来的,支持STOMP, AMQP, MQTT, Openwire, SSL, and WebSockets 等多种协议. A ...
- 新概念英语(1-55)The Sawyer family
新概念英语(1-55)The Sawyer family When do the children do their homework? The Sawyers live at 87 King Str ...
- OAuth2.0学习(1-13)oauth2.0 的概念:资源、权限(角色)和scope
mkk 关于资源的解释 : https://andaily.com/blog/?cat=19 resource用于将系统提供的各类资源进行分组管理, 每一个resource对应一个resource-i ...
- hdu2050 折线分割平面---递推
题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=2050 题目大意: 求n条折线分割平面的最大数目 思路: 先看n条直线的时候 一条直线 2个平面 两条 ...
- MongDB配置方法
先下载安装包 安装 方法一:命令行启动 在 C:\MongoDB\Server\3.4目录下建立data文件夹, data里面建立db文件夹 bin目录下运行 mongod --dbpath C:\M ...
- Jenkins的安装
安装环境: 512M内存 10G硬盘空间 Java 8环境 先来创建jenkins的运行目录: mkdir /data/jenkins && cd /data/jenkins 下载je ...