且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C#定时器毫秒等待

更新时间:2023-02-27 07:39:00


我需要在C#的方式来等待剩下的( X - 。actual_time)毫秒


块引用>

我相信这是在Windows上运行的C#



还有就是你的问题。 Windows是不是实时的操作系统。



如果您需要毫秒级的计时精度是设置线程的线程优先级非常高,然后在查询高性能忙等待你能做的***的计时器(秒表)。



您不能屈服于另一个线程;其他线程可以运行多达16毫秒操作系统上下文切换之​​前,当然,除非你是最高优先级的线程,你有没有保证,控制那些16毫秒后回来你了。



现在,设置线程优先级高,则忙等待是最无礼的事情你能做之一;本质上,你将采取在用户机器的控制权,而不是让他们做别的吧。



所以我会做什么是的放弃这个行动完全的。无论是,(1)考虑获得操作系统设计的实时过程控制,如果这是其实你的应用程序,而不是一个操作系统,专为多任务一堆业务线应用程序。或者(2)放弃你的要求,即动作恰好发生每25毫秒。只是执行计算一次,并得到您的量子其余到另一个线程。当你得到控制回来,看看你既然产生了超过25 ms是否已过;若没有,再次产生。如果有,重新开始和进行计算。


Every n*x milliseconds I perform an action where n = 0, 1, 2, ...; x is some increment.

Example - every 25 milliseconds I perform a calculation.

This action can take fewer than x seconds for each increment. As a result, I need a way in C# to wait the remaining (x - actual_time) milliseconds.

Example - if the calculation only takes 20 milliseconds, I need to wait 5 more milliseconds before re-running the calculation.

Please advise.

Thanks, Kevin

I need a way in C# to wait the remaining (x - actual_time) milliseconds.

I presume that is C# running on Windows.

And there is your problem. Windows is not a "realtime" operating system.

The best you can do if you need millisecond-grade timing precision is to set the thread priority of your thread extremely high, and then busy-wait while querying the high performance timer (Stopwatch).

You cannot yield to another thread; the other thread could run for as much as 16 milliseconds before the operating system context switches it, and of course unless you are the highest priority thread, you have no guarantee that control is coming back to you after those 16 milliseconds are up.

Now, setting thread priority high and then busy waiting is one of the most rude things you can possibly do; essentially you will be taking control of the user's machine and not allowing them to do anything else with it.

Therefore what I would do is abandon this course of action entirely. Either, (1) consider obtaining an operating system designed for realtime process control if that is in fact your application, rather than an operating system designed for multitasking a bunch of line-of-business applications. Or (2) abandon your requirement that the action happen exactly every 25 milliseconds. Just perform the calculation once and yield the remainder of your quantum to another thread. When you get control back, see if more than 25 ms has passed since you yielded; if it has not, yield again. If it has, start over and perform the calculation.