如何在 C# 中仅引发 1 个计时器事件?

发布于 2024-09-12 17:14:37 字数 117 浏览 1 评论 0原文

如何让计时器事件一次触发一个。 例如,我有一个计时器,每 10 分钟引发一次事件。 引发的事件需要 10 分钟或更长时间才能完成执行。 我希望计时器在活动结束后重置。 换句话说,我不想在任何时候引发超过 1 个事件实例。

How do I get a timer event to fire one at a time.
For example I have a timer that raises an event every 10 minutes.
The event that is raised takes 10 or more minutes to finish executing.
I would like the timer to reset AFTER the event has finished.
In other words I do not want to raise more than 1 instance of the event at any one time.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

坦然微笑 2024-09-19 17:14:37

使用 System.Timers.Timer 而不是 Threading

将 AutoReset 设置为 false。

然后完成后再次启动。

Use System.Timers.Timer not the Threading one

Set AutoReset to false.

Then Start it again when you're done.

去了角落 2024-09-19 17:14:37

通常我所做的是让我的事件在引发时停止计时器,然后在事件过程完成时重新启动计时器:

private void timerHandler(object sender, TimerElapsedEventArgs e)
{
    Timer timer = (Timer)sender;
    timer.Stop();
    RunProcess();
    timer.Start();
}

public void RunProcess()
{
    /* Do stuff that takes longer than my timer interval */
}

现在我的计时器将在过程完成后再次启动

Usually what I do is have my event stop the timer when it's raised and then restart the timer when the event process completes:

private void timerHandler(object sender, TimerElapsedEventArgs e)
{
    Timer timer = (Timer)sender;
    timer.Stop();
    RunProcess();
    timer.Start();
}

public void RunProcess()
{
    /* Do stuff that takes longer than my timer interval */
}

Now my timer will start again on completion of the process

浪推晚风 2024-09-19 17:14:37

为了效率或逻辑而停止计时器可能很困难。以下代码同步跳过事件。

static readonly object key = new object();

void TimerHandler(object sender, TimerElapsedEventArgs e)
{
  if(Monitor.TryEnter(key))
  {
    try
    {
      //do your stuff
    }
    finally
    {
      Montitor.Exit(key);
    }
  }
}

It may be difficult to stop timers for efficiency or logic. The following code synchronizes skipping the events.

static readonly object key = new object();

void TimerHandler(object sender, TimerElapsedEventArgs e)
{
  if(Monitor.TryEnter(key))
  {
    try
    {
      //do your stuff
    }
    finally
    {
      Montitor.Exit(key);
    }
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文