关于C#定时器的一些问题

wl0326 2012-06-15 04:48:34
各位高手
我有一个定时器问题想请教一下,因为系统需要10ms执行一次事件,我发现System.Timers.Time和System.Thread定时都会有比较大的误差,上网查了一下说Windows API函数有个timeGetTime()函数比较精确,可我用它变了一个小程序测试一下却发现我的程序有问题不知到该怎么定时,希望各位不惜帮忙修改一下,如若可以也希望大家可以提供几个定时函数供小弟参考,感激不尽,以下是我的测试程序。
[DllImport("winmm")]
static extern uint timeGetTime();
[DllImport("winmm")]
static extern void timeBeginPeriod(int t);
[DllImport("winmm")]
static extern void timeEndPeriod(int t);
static void Main(string[] args)
{
int i1 = 1;
for (int i = 0; i < 100; i++)
{
timeBeginPeriod(1);
uint start = timeGetTime();
while (true)
{
//uint t1 = timeGetTime();
//uint t = t1 - start;
if (timeGetTime() - start >= 9 && timeGetTime() - start <= 10)
{
Console.WriteLine(timeGetTime() - start);
i1++;
break;
}


}
timeEndPeriod(1);

}


////单位毫秒

Console.WriteLine(i1);
Console.ReadKey();

发现一直会进入死循环,难道这个定时器精度也不是1ms,希望大家帮忙指正,提供一些可以实现10ms功能的功能的定时函数,真的很谢谢了。
...全文
273 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
没那么正好让你满足if (timeGetTime() - start >= 9 && timeGetTime() - start <= 10)的条件,如果赶上了,属你幸运

mizuho_2006 2012-06-15
  • 打赏
  • 举报
回复
http://topic.csdn.net/u/20120514/16/0235fd54-b240-4035-90a5-04960c52524a.html

「翻译」C# 中的高性能计时器
bdmh 2012-06-15
  • 打赏
  • 举报
回复
没那么正好让你满足if (timeGetTime() - start >= 9 && timeGetTime() - start <= 10)的条件,如果赶上了,属你幸运

Windows NT:该函数的时间精度是五毫秒或更大一些,这取决于机器的性能
glongsoft 2012-06-15
  • 打赏
  • 举报
回复
这个最好自己写,也不难,没有好的现成的函数!
glongsoft 2012-06-15
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 的回复:]
while(true)
{
//......
Thread.Sleep(10);
}
[/Quote]
最好在开始和结束时打印一下系统时间,明确程序执行用了多长时间(虽然可能十分小)
wl0326 2012-06-15
  • 打赏
  • 举报
回复
Thread.Sleep(10);
有误差啊,我要的是精确定时
__天涯寻梦 2012-06-15
  • 打赏
  • 举报
回复
while(true)
{
//......
Thread.Sleep(10);
}

111,126

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧