2010-09-19 67 views
0

我有一个父类,其中包含一个对象的数组,每个对象都有一个与它关联的计时器。C#WinForm定时器 - 通知父类,定时器事件已被提出

我希望父类能够启动和停止这些定时器,并且最重要的是希望父类能够检测哪个子对象的'定时器已经过期'甚至已经被引发。

这是可能的,如果是这样做,最好的办法是什么?

回答

1

我建议你给子对象一个事件,当定时器被触发时可以引发。然后,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); 
    } 
} 
+0

非常感谢,这工作完美! – Riina 2010-09-19 16:35:07