C# 是否有任何原因导致计时器自动重置为false,但在其已过事件期间重新启动自身?
我只是偶然碰到了这个代码,我不明白它。是否有理由使用这种设计,而不只是使用AutoReset true重新运行已运行的代码C# 是否有任何原因导致计时器自动重置为false,但在其已过事件期间重新启动自身?,c#,timer,C#,Timer,我只是偶然碰到了这个代码,我不明白它。是否有理由使用这种设计,而不只是使用AutoReset true重新运行已运行的代码 private readonly Timer Timer = new Timer(); protected override void OnStart(string[] args) { Logger.InfoFormat("Starting {0}.", ServiceName); try { // If Enabled is
private readonly Timer Timer = new Timer();
protected override void OnStart(string[] args)
{
Logger.InfoFormat("Starting {0}.", ServiceName);
try
{
// If Enabled is set to true and AutoReset is set to false, the Timer raises the Elapsed event only once, the first time the interval elapses.
Timer.AutoReset = false;
Timer.Elapsed += Timer_Elapsed;
Timer.Interval = Settings.Default.ScriptingStatusLifeTime;
Timer.Start();
}
catch (Exception exception)
{
Logger.ErrorFormat("An error has occurred while starting {0}.", ServiceName);
Logger.Error(exception);
throw;
}
}
/// <summary>
/// Whenever the Schedule Service time elapses - go to the ScriptingStatus table
/// and delete everything created earlier than 1 hour ago (by default, read from ScriptingStatusLifeTime)
/// </summary>
private void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
try
{
// ScriptingStatusLifeTime defaults to 60 minutes.
DateTime deleteUntil = DateTime.Now.AddMilliseconds(Settings.Default.ScriptingStatusLifeTime * -1);
Logger.InfoFormat("Clearing all ScriptingStatus entries with ControlDate before: {0}.", deleteUntil);
RemoteActivator.Create<RemoteScriptingStatus>().DeleteUntil(deleteUntil);
}
catch (Exception exception)
{
Logger.Error(exception);
}
finally
{
Timer.Start();
}
}
private readonly Timer=new Timer();
启动时受保护的覆盖无效(字符串[]args)
{
InfoFormat(“启动{0}.”,ServiceName);
尝试
{
//如果Enabled设置为true,AutoReset设置为false,则计时器仅在间隔第一次经过时引发已用事件一次。
Timer.AutoReset=false;
Timer.appeated+=Timer\u appeated;
Timer.Interval=Settings.Default.ScriptingStatusLifeTime;
Timer.Start();
}
捕获(异常)
{
ErrorFormat(“启动{0}时出错。”,ServiceName);
记录器错误(异常);
投掷;
}
}
///
///每当计划服务时间结束时,转到ScriptingStatus表
///并删除早于1小时前创建的所有内容(默认情况下,从ScriptingStatusLifeTime读取)
///
私有无效计时器\u已过(对象发送器,ElapsedEventArgs e)
{
尝试
{
//ScriptingStatusLifeTime默认为60分钟。
DateTime deleteTill=DateTime.Now.addmillizes(Settings.Default.ScriptingStatusLifeTime*-1);
InfoFormat(“清除ControlDate在:{0}之前的所有ScriptingStatus条目”,deleteUntil);
RemoteActivator.Create().deleteUtil(deleteUtil);
}
捕获(异常)
{
记录器错误(异常);
}
最后
{
Timer.Start();
}
}
此外,我正在这段代码中寻找memoryleak
我刚刚读了这篇文章:这似乎意味着我的计时器对象需要正确处理。我在当前文件中未看到任何要处理的调用。我想知道这个计时器事件是否也会导致泄漏?据我所知,通过将
AutoReset
设置为true,触发的计时器事件可能会在事件执行时间超过超时值的地方重叠
例如,超时时间为10秒,但工作负载为1分钟
但是,如果AutoReset
为false,则计时器事件将只触发一次。您可以在事件中重新启动计时器,并且计时器可以继续
在本例中,这意味着计时器可以在10秒后启动,但如果事件持续时间超过10秒,则没有重叠,它将在工作完成后重新启动
我就是这样做的,在示例代码中也是这样
附录:只有在未设置同步对象的情况下,上述情况才是正确的,这是因为在线程池上引发了已用事件。如果您设置了一个sync对象,那么我希望锁定能够阻止经过的事件,以便一次只能触发一个事件