【发布时间】:2014-05-27 12:45:49
【问题描述】:
在这个Link 中,它展示了如何确定计时器是否正在运行。对我来说它不起作用。
我在静态类中声明了计时器,如图所示
public static class ServiceGlobals // Globals
{
public static System.Timers.Timer _timer = new System.Timers.Timer();
}
}
在我的服务启动时,我设置了计时器属性
protected override void OnStart(string[] args)
{
ServiceGlobals._timer.AutoReset = false;
ServiceGlobals._timer.Interval = (3000);
ServiceGlobals._timer.Elapsed += new System.Timers.ElapsedEventHandler(_timer_Elapsed);
ServiceGlobals._timer.Enabled = true;
ServiceGlobals._timer.Start(); // Start timer
}
然后我检查它是否在我的一种方法中运行,但即使它正在运行,代码也总是错误的
if (ServiceGlobals._timer.Enabled) // Check if the timer is running
{
// Return error.........
}
【问题讨论】:
-
试试这个,看看它会返回什么。
ServiceGlobals._timer.Enabled = true;if (ServiceGlobals._timer.Enabled){} -
旁注:1.您不应该公开公共字段。 2.非公共成员应该有“PascalCase”命名约定,没有前缀。
-
我们已经可以从您之前的问题中看出您的 Interval 属性太短了。所以是的,你得到 false 的几率非常高,因为 Elapsed 事件处理程序正在运行。但是不能保证。使用布尔变量来跟踪。请注意不可避免的竞争条件,停止计时器不会停止 Elapsed 事件处理程序的运行,也不会阻止您再次启用计时器。如果你已经厌倦了这门课,那么have a look here.
标签: c# timer system.timers.timer