2010-09-19 59 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