开发者

C# WinForm Timers - Notify parent class that a timer event has been raised

开发者 https://www.devze.com 2023-01-16 14:29 出处:网络
I have a parent class that contains an array of objects each with a timer associated with it. I want the parent class to be able to start and stop these timers, and most importantly want the parent c

I have a parent class that contains an array of objects each with a timer associated with it.

I want the parent class to be able to start and stop these timers, and most importantly want the parent class to detect which of the it's child objects 'timer elapsed' even has been raised.

Is this possible and if so what is the best w开发者_如何转开发ay to do it?


I would suggest that you give the child objects an event that can be raised when the Timer is fired. Then the Parent class can attach a handler to the event from each child.

Here is some pseudo code to give you an idea of what I mean. I have purposely not shown any WinForms or Threading code, because you do not give much detail in that area.

class Parent
{
  List<Child> _children = new List<Child>();

  public Parent()
  {
    _children.Add(new Child());
    _children.Add(new Child());
    _children.Add(new Child());

    // Add handler to the child event
    foreach (Child child in _children)
    {
      child.TimerFired += Child_TimerFired;
    }
  }

  private void Child_TimerFired(object sender, EventArgs e)
  {
    // One of the child timers fired
    // sender is a reference to the child that fired the event
  }
}

class Child
{
  public event EventHandler TimerFired;

  protected void OnTimerFired(EventArgs e)
  {      
    if (TimerFired != null)
    {
      TimerFired(this, e);
    }
  }

  // This is the event that is fired by your current timer mechanism
  private void HandleTimerTick(...)
  {
    OnTimerFired(EventArgs.Empty);
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消