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 ...
随机推荐
- 使用HttpClient4.5实现HTTPS的双向认证
说明:本文主要是在平时接口对接开发中遇到的为保证传输安全的情况特要求使用https进行交互的情况下,使用httpClient4.5版本对HTTPS的双向验证的 功能的实现 首先,老生常谈,文章 ...
- machine learning 之 导论 一元线性回归
整理自Andrew Ng 的 machine learnig 课程 week1. 目录: 什么是机器学习 监督学习 非监督学习 一元线性回归 模型表示 损失函数 梯度下降算法 1.什么是机器学习 Ar ...
- WPS怎么让前几页的页眉或者页脚与后面的不同
其实不管利用WPS还是office对文档还是PPT进行操作,其实核心思想还是一种编程,主要是前端的编程,就是通过改变一些这些软件设置的样式,然后通过改变这些样式,使这些文字以老师要求的格式显示出来的, ...
- DSkin 的WebUI开发模式介绍,Html快速开发Winform的UI
新版WebUI开发模式采用MiniBlink内核,这个内核功能更完善,dll压缩之后才5M,而且提供开发者功能,内核还在更新中,而且是开源项目:https://github.com/weolar/mi ...
- angular2 学习笔记 ( app initialize 初始化 )
refer : http://stackoverflow.com/questions/39033835/angularjs2-preload-server-configuration-before-t ...
- copy代码(含static对象)留下的致命错误
本来以为这个bug快改不好了,然而发现了问题所在 copy代码没有完全改掉对象名称,导致对象重复创建了,由于是static所以debug过程中 注释了addProperty(gridRowDetail ...
- CodeForces 1B-字符串,进制转换与数学
一个萌新的成长之路 Background 同学们都回家了,只有我和wjh还有邢神在机房敲代码,吃random口味的方便面-- Description Translated by @PC_DOS fro ...
- Python 爬虫基础知识
requests Python标准库中提供了:urllib.urllib2.httplib等模块以供Http请求,但是,它的 API 太渣了.它是为另一个时代.另一个互联网所创建的.它需要巨量的工作, ...
- Java-NIO(九):管道 (Pipe)
Java NIO 管道是2个线程之间的单向数据连接.Pipe有一个source通道和一个sink通道.数据会被写到sink通道,从source通道读取. 代码使用示例: @Test public vo ...
- LabelFrame
LabelFrame组件是Frame组件的变体. 默认情况下,LabelFrame会在其子组件的周围绘制一个边框以及一个标题. 何时使用LabelFrame组件?当你想要奖一些相关的组件分为一组的时候 ...