C#定时器毫秒等待 [英] C# Timer for Millisecond Waits

查看:1274
本文介绍了C#定时器毫秒等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每n * X毫秒我执行的操作,其中n = 0,1,2,...; X是一些增量



示例 - 每25毫秒我执行计算



这动作可以少走比x秒对每个增量。其结果是,我需要在C#办法以等待剩余的(X - actual_time)毫秒



示例 - 如果计算只需要20毫秒,我需要重新运行计算之前要等待5个毫秒。



请指教。



谢谢,
凯文


解决方案

我需要在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.

这篇关于C#定时器毫秒等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆