了解 C# 中 Timer 控件的工作 [英] Understanding working of Timer control in C#

查看:24
本文介绍了了解 C# 中 Timer 控件的工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个 Timer 控件,其间隔设置为 20 毫秒.在这个控件中,我正在做一些需要 100 毫秒才能完成的操作.那么一旦它执行了该操作,Timer 控件是否会在不等待该操作完成的情况下再次执行?或者直到那个操作没有完成,Timer才不会再次执行?

Let's say I have a Timer control with interval set to 20ms. Inside this control I am doing some operation that takes 100ms to complete. So once it is doing that operation, will Timer control execute again without waiting for that operation to finish? Or until that operation is not finished, Timer will not execute again?

编辑
我在控制台应用程序的单独线程中使用 System.Timers.Timer().在与下面的安德鲁讨论后,我编辑了我的问题.

EDIT
I am using System.Timers.Timer() in a separate thread in console application. I have edited my question after discussing with Andrew below.

推荐答案

System.Timers.Timer 在随机"线程池线程上运行和引发事件.回调和计时器滴答将同时运行,这意味着在间隔小于方法终止所需的时间的情况下,您将重叠执行这些事件.

System.Timers.Timer both runs and raises events on a 'random', thread pool thread. The callbacks and the timer ticks will run concurrently, meaning you would have overlapping execution of these events in your situation where the interval is less than the time the method takes to terminate.

即使这种行为与我在下面发布的行为不同,您仍然不想这样做.结果将是线程池最终会耗尽.它也可能不是您想要的功能.

Even though this behavior is different from that which I posted about below, you still don't want to do this. The result will be that the thread pool will eventually become exhausted. It is also probably not your desired functionality.

一种解决方案是对其进行编码,使其无法并发执行.

A solution would be to code it such that concurrent execution is not possible.

  1. 测试一些静态字段以查看现有迭代是否正在运行,如果是,则取消新"实例.应通过内存屏障测试/设置此类字段.
  2. 进入事件后停止计时器,运行代码,然后再次启动它.如果您愿意,您可以根据执行所需的时间调整间隔.
  3. 不要做简单的锁定来阻止并发执行,直到前一个完成;这将回到我用 Windows Forms Timer 描述的问题(减去 UI 锁定)

<小时>

上一个答案

当我以为您说的是 System.Windows.Forms 中的计时器并在 Windows 窗体程序中使用它时,这是我发布的旧答案.由于情况并非如此,以下信息不适用于您.但我把它留在这里,以防它对其他人有帮助.

因为 System.Windows.Forms 命名空间中的 Timer 控件在 UI 线程上运行,它的回调也是如此,所以您的滴答事件会堆积起来,等待当前正在执行的操作完成.您的 UI 也将被锁定在持续时间内.

Because the Timer control inside the System.Windows.Forms namespace runs on the UI thread, as does its callback, your tick events will pile up, waiting for currently executing operations to complete. You UI will also be locked in the duration.

因此,您不想这样做.您的程序将锁定.

Therefore, you do not want to do this. Your program will lock up.

这篇关于了解 C# 中 Timer 控件的工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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