如何在winforms中使用计时器创建一个准确的时间段 [英] How I can create an accurate period using timer in winforms
问题描述
大家好,
我的目的是创建一个周期性函数,其中OnTimeEvent在两个连续时间之间的经过时间恰好等于计时器的间隔。然后我可以使用间隔时间作为采样时间。
我尝试过:
我在C#中使用timer elapse事件来创建一个周期性函数。
即使Timer间隔设置为10ms,但是当我测量经过时间时,变化的范围是12-30ms,即使OnTimeEvent函数中有几行代码(我测量它大约是1-3ms)。
如何在C#中完成它,我应该使用Thread任务吗?或者另一种方法。
请建议我一个可以解决我问题的解决方案。
非常感谢你!
基于时间戳的计时器不适用于小间隔。
从我的观点来看,基于线程的计时器将是最佳方案。您还可以查看多媒体计时器(Windows) [ ^ ]。
但是你应该知道Windows不是实时操作系统。你不会得到恒定的计时器间隔;特别是当系统负载很高或有很多磁盘或网络数据传输时。
一些CP链接:
Microsecond和毫秒C#计时器 [ ^ ]
.NET Framework的多媒体计时器 [ ^ ]
提供不同解决方案的SO线程:
c# - Most .NET中的准确计时器? - Stack Overflow [ ^ 一>
Hi everyone,
My purpose is to create a periodical function which the elapse time of OnTimeEvent between two continuous times is exactly equal to the interval of the timer. Then I can use the interval time as sampling time.
What I have tried:
I am using timer elapse event in C# to create a periodical function.
Even though the Timer interval is set to 10ms, but when I measure the elapsed time is varied in the range of 12-30ms, even though there are several lines of code in the OnTimeEvent function (I measure it is about 1-3ms).
How I can do it in C#, should I use Thread task? or another method.
Please suggest me a solution that can solve my problem.
Thank you so much!
Tick based timers won't work for small intervals.
From my point of view a thread based timer would be the best solution. You might also have a look at the Multimedia Timers (Windows)[^].
But you should be aware that Windows is not a real time operating system. You will not get constant timer intervals; especially when the system load is high or there are many disk or network data transfers.
Some CP links:
Microsecond and Millisecond C# Timer[^]
The Multimedia Timer for the .NET Framework[^]
An SO thread providing different solutions:
c# - Most accurate timer in .NET? - Stack Overflow[^]
这篇关于如何在winforms中使用计时器创建一个准确的时间段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!