views:

78

answers:

1

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 way to do it?

+1  A: 

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);
  }
}
Chris Taylor
Thanks a lot this worked perfectly!
Riina