是否有任何理由使Timer具有错误的AutoReset,但在其过去的事件期间重新启动?

Sea*_*son 13 c# timer

我刚碰到这个代码,我不明白.是否有理由使用此设计而不是仅使用AutoReset重新运行已用代码?

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

此外,我正在寻找此代码中的内存泄漏.

我刚读过这篇文章:如果autoreset设置为false,我的计时器会自动处理吗?这似乎暗示我的Timer对象需要正确处理.我没有在当前文件中看到任何对Dispose的调用.我想知道这个Timer_Elapsed事件是否也引入了泄漏?

Llo*_*oyd 32

据我所知,由于必须AutoReset为true,被触发的计时器事件可能会重叠,而事件执行所需的时间超出了超时值.

例如,超时10秒但工作量为1分钟.

但是如果AutoReset为false,那么timer事件只会触发一次.您可以在事件中重新启动计时器,计时器可以继续.

在示例中,这意味着计时器可以在10秒后触发,但如果事件花费的时间超过10秒,则没有重叠,它将在工作完成后重新启动.

这几乎是我如何做到的,以及你如何在示例代码中使用它.

附录:如果您没有设置同步对象,则上述情况才适用,这是因为在线程池上引发了已发生的事件.如果你设置了一个同步对象,那么我希望锁定可以阻止已经过去的事件,这样一次只能触发一个事件.

  • 哦 这是一个公平的观点。有趣。 (2认同)