用于毫秒等待的 C# 计时器 [英] C# Timer for Millisecond Waits

查看:46
本文介绍了用于毫秒等待的 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 毫秒以上;如果没有,再次屈服.如果有,重新开始计算.

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天全站免登陆