有没有一种方法可以为多个事件使用一个计时器?

4

我正在使用C# .NET 3.5。 当计时器到期并执行事件处理程序时会发生什么? 计时器是否停止存在? 我可以在一个计时器上注册多个不同时间的事件,期望它们依次触发吗?


1
一个计时器只能计时一个时间间隔。这已经足够用于计时任何数量的事件,您只需要将时间间隔设置为最早到期的那个即可。 - Hans Passant
@Grant 我同意它不应该在未处理/删除的情况下停止存在。我还假设,注册多个Ticks应该是可能的。但可能行为取决于计时器类型。在.NET中,我知道有3个(+1个在ASP中)。因此,我想知道哪一个/哪些将在预期时间间隔内给我所需的单独事件触发。 - Sold Out
@Hans 您能否重新表述一下“您只需将间隔设置为最早到期的间隔。”我不确定我是否正确理解了您的意思。 - Sold Out
假设你今天有4个约会,但只有一只手表。你不会因此而迟到任何一个约会,对吧?在代码中也是同样的道理。 - Hans Passant
1个回答

1

You can set a timer to fire off the event only once or continue to do it (Timer.AutoReset property). Yes, you can register several different event handlers on a single timer, but I don't know that there is any way of knowing what order they will fire. If that matters to you, set a single handler, and have that handler call the others. If what you are trying to do is to call a different handler, each time the timer goes off, I would suggest setting a single handler that keeps an enum indicating which function to call and incrementing it each time it gets called by the timer.

To call the same handler to "iterate" through a list of parameters, once on each interval elapsed, I would have an array or list of the parameters and the handler would just increase a counter or consume the list.

using System.Timers;

public class MyTimedDelete {

  private static List<int> ListOfIds=null;
  private static System.Timers.Timer myTimer=null;

  public static void AddIdToQueue(int id)
  {
      if (ListOfIds == null)
      {
         ListOfIds = new List<int>();
         myTimer = new System.Timers.Timer(2000);
         myTimer.Elapsed += OnTimedEvent;
      }

      ListOfIds.Add(id);
      if (ListOfIds.Count==1)
      {
          myTimer.Start();
      }    
  }

  private static void OnTimedEvent(Object source, ElapsedEventArgs e)
  {
      deleteItem(ListOfIds[0]);
      ListOfIds.RemoveAt(0);
      if (ListOfIds.Count == 0) {
          myTimer.Stop();
      }
  }
}


我需要启动相同的处理程序,但使用不同的参数(要删除的消息的 ID)。 - Sold Out
那么我在上面回答中添加的代码就能够起作用了,对吧? - user4843530
这个问题已经有解决方案了。你建议在SomeFunction中创建一个新的计时器,但我需要一个通用计时器,在消息到达时启动额外的倒计时(相同的时间间隔)。当时间间隔过去时,计时器将触发已过去事件处理程序,并将msgId作为参数传递。该消息将从队列中删除。 - Sold Out
那只是我之前所说的内容的扩展。我已经在代码中详细展开了。如果你有这样一个类,在你的代码的任何地方,你可以调用MyTimedDelete.AddIdToQueue(x);将id添加到队列中,并在经过一段时间后让定时事件调用你的deleteItem函数来处理该id。我还没有构建这个类,所以里面可能有错别字。由你来构建和测试。 - user4843530
@Gichrist 感谢您的帖子。 这个更接近我所需要的。 但是正如我所提到的,我需要使用一个额外的参数 - msgId来触发OnTimedEvent,以便我不依赖时间顺序来删除正确的消息。 此外,如果收到我发送的消息(即msgId)的确认,我需要停止计时器。 在这种情况下,我仅需要停止此msgId的计时器,以便不会调用具有此msgId的OnTimedEvent。 在最坏的情况下,我可以忽略那个调用,但这并不是一个干净的解决方案。尽管如此,您的帖子很有趣,所以我投了1+。 再次感谢。 - Sold Out
显示剩余2条评论

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