c# - 不使用 ThreadPool 的 C# 中的周期性任务

标签 c# multithreading timer

有没有一种方法可以在不使用线程池的情况下在 C# 中执行周期性任务/线程(这是我的主要要求之一)。

预期的场景如下:

  1. 周期性线程阻塞/等待计时器事件(来自系统)。
  2. 系统会在计时器到期时通知线程。
  3. 线程执行一些代码。
  4. 线程阻塞/等待来自系统的下一个计时器事件(请注意,如果线程错过了一个或多个计时器事件,这没关系)。

我发现与此最接近的是 System.Forms.Timer,但问题是它的精度限制为 55 毫秒,这对我来说不够。

System.Timers.Timer 似乎能够通过 SynchronizingObject 属性处理此问题。但是,我不太确定如何根据上述情况实现 ISynchronizeInvoke。我找到的所有用于实现 ISynchronizeInvoke 的代码示例对于处理这样一个简单的场景来说似乎都太复杂了。

有没有一种方法可以像上述场景(不使用线程池)一样在 C# 中轻松实现此功能,并且比 System.Forms.Timer 更准确?

最佳答案

Windows 计时器的默认分辨率为 15.6 毫秒,来自其 documentation :

The default system-wide timer resolution in Windows is 15.6 ms, which means that every 15.6 ms the operating system receives a clock interrupt from the system timer hardware. When the clock interrupt fires, Windows updates the timer tick count and checks whether a scheduled timer object has expired. Some applications require that timer expiration is serviced more frequently than once every 15.6 ms.

他们还声明:

Applications can call timeBeginPeriod to increase the timer resolution. The maximum resolution of 1 ms is used to support graphical animations, audio playback, or video playback. This not only increases the timer resolution for the application to 1 ms, but also affects the global system timer resolution, because Windows uses at least the highest resolution (that is, the lowest interval) that any application requests. Therefore, if only one application requests a timer resolution of 1 ms, the system timer sets the interval (also called the “system timer tick”) to at least 1 ms. For more information, see “timeBeginPeriod Function” on the MSDN® website.

所以如果你真的需要高分辨率计时器,你可以使用timeBeginPeriod调用以影响全局系统计时器,但知道它会影响它正在运行的设备的电池生命周期/功耗。

此外,还有 QueryPerformanceCounterQueryPerformanceFrequency可用于在 .net 中获得较低精度级别的调用,如本例所示:http://www.codeproject.com/Articles/571289/Obtaining-Microsecond-Precision-in-NET

关于c# - 不使用 ThreadPool 的 C# 中的周期性任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19341345/

相关文章:

java - 如何使用Swing Timers来制定整体更新率?

c# - MQQueue 中的 PutReplyMessage 和 PutReportMessage 的用途是什么?

android - 线程错误

c# - 如何识别方法中的当前线程?

java - Android:静态变量和移动复杂数据

Java:如何使滚动条以恒定速度滚动?

python - 使用 python-asyncio 创建对绑定(bind)方法的临时异步计时器回调

c# - 在 LINQ 中混合 Any() 和 First()?

c# - 如何检索 StructureMap 中所有命名实例的名称

c# - 从另一个 View 返回数据 Xamarin.iOS