繁体   English   中英

C#WinForm计时器-通知父类已引发计时器事件

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

我有一个父类,其中包含一个对象数组,每个对象都有一个与之关联的计时器。

我希望父类能够启动和停止这些计时器,最重要的是希望父类检测“计时器已逝”的子对象中的哪一个甚至被引发。

这可能吗,如果可以,最好的方法是什么?

我建议您给子对象一个事件,当计时器被触发时可以引发该事件。 然后,Parent类可以将处理程序附加到每个孩子的事件中。

这是一些伪代码,可让您了解我的意思。 我故意没有显示任何WinForms或Threading代码,因为您在该领域没有提供太多详细信息。

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);
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM