计时器的AutoReset属性为false,但在其Elapsed事件期间自行重新启动,是否有任何原因?

14

我刚刚遇到了这段代码,但是我不理解它。使用这种设计,有什么理由而不是使用AutoReset true重新运行经过的代码吗?

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();
    }
}

此外,我正在查找这段代码中的内存泄漏。

我刚刚阅读了这篇帖子:如果将autoreset设置为false,我的计时器会自动释放吗?,它似乎暗示着我的计时器对象需要正确地进行释放。我没有在当前文件中看到任何Dispose的调用。我想知道这个Timer_Elapsed事件是否也引入了一个泄漏?

1个回答

38
据我所知,如果将AutoReset 设置为true,则定时器事件触发时,事件执行所需的时间超过超时值时,它们可以重叠。
例如,设置超时时间为10秒,但工作量为1分钟。
然而,如果将AutoReset 设置为false,则定时器事件仅会触发一次。您可以在事件中重新启动定时器并使其继续运行。
在此示例中,这意味着定时器可以在10秒后触发,但如果事件执行时间超过10秒,则没有重叠,定时器将在完成工作后重新启动。
这基本上是我的操作方式,也是您在示例代码中的操作方式。
附言:以上内容仅适用于未设置同步对象的情况,因为已经在线程池上引发了经过的事件。如果设置了同步对象,则希望锁定阻止经过的事件,以便一次只能触发一个事件。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接