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

发布于 2024-09-19 22:54:15 字数 135 浏览 6 评论 0原文

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

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

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

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?

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

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

发布评论

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

评论(1

满地尘埃落定 2024-09-26 22:54:15

我建议您为子对象提供一个在计时器触发时可以引发的事件。然后,父类可以将处理程序附加到每个子类的事件。

这是一些伪代码,可以让您了解我的意思。我故意没有展示任何 WinForms 或线程代码,因为您没有提供该领域的太多细节。

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

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);
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文