c# - 通过线程以一定的时间间隔执行任务一定次数

标签 c# multithreading

我对线程没有太多经验。我正在使用 .NET 4,并且想使用 .NET 4 线程功能来解决这个问题。这就是我想做的。

我有一个包含两种方法的类,“A”和“B”。我希望“A”每隔一定毫秒数(例如 3000)调用“B”一定次数(例如 100)。我想记录方法“B”执行 100(或其他)次后的平均执行时间。该类将有一些私有(private)属性来跟踪“B”的总执行时间,以便计算平均值。

我不确定方法“A”是否应该通过 System.Timers.Timer 线程调用“B”(可以设置间隔,但不能设置次数)或者是否有更好的(.NET 4)这样做的方法。

非常感谢。

最佳答案

在阅读您的问题时,我认为您的根本问题是如何安全地启动一组事件并以线程安全的方式计时它们的执行。在您的示例中,您每 3000 毫秒运行 100 次迭代。这意味着每次迭代最多只需要 30 毫秒。不幸的是,System.Timers.Timer(它是带有包装器的System.Threading.Timer)并不那么精确。预计精度最多为 10 毫秒,甚至可能更差。为了获得您真正需要的 1 毫秒精度,您将需要利用 native 互操作。这是我找到的一句话:

The precision of multithreaded timers depends on the operating system, and is typically in the 10–20 ms region. If you need greater precision, you can use native interop and call the Windows multimedia timer. This has precision down to 1 ms and it is defined in winmm.dll. First call timeBeginPeriod to inform the operating system that you need high timing precision, and then call timeSetEvent to start a multimedia timer. When you’re done, call timeKillEvent to stop the timer and timeEndPeriod to inform the OS that you no longer need high timing precision. You can find complete examples on the Internet that use the multimedia timer by searching for the keywords dllimport winmm.dll timesetevent

-Joseph Albahari ( http://www.albahari.com/threading/part3.aspx )

如果您遵循他的建议,您应该获得所需的精度。

关于c# - 通过线程以一定的时间间隔执行任务一定次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5952531/

相关文章:

c# - 将 Google 日历解析为 DDay.iCal

c# - 尝试添加分数钱或水时出错

c# - 以编程方式确定项目解决方案中的索引 - C#

c# - 多个代码块被同一个对象锁定

c++ - 为什么在此代码块中使用 condition_variable?

c# - 为什么我们指定一个委托(delegate)和一个事件,为什么不在 C# 中使用一个事件?

c# - 使用 $.post 或 $.get 返回可下载的 zip 文件

c++ - 互斥锁映射c++11

c# - 将信息同步保存到文件的最佳方式

java - 如何在 servlet 上运行一些在 servlet 发送响应后继续运行的东西?