【发布时间】:2010-09-19 12:07:50
【问题描述】:
我有一个父类,其中包含一个对象数组,每个对象都有一个与之关联的计时器。
我希望父类能够启动和停止这些计时器,最重要的是希望父类能够检测到它的哪个子对象“计时器已过”甚至已被引发。
这可能吗?如果可以,最好的方法是什么?
【问题讨论】:
标签: c# winforms multithreading timer
我有一个父类,其中包含一个对象数组,每个对象都有一个与之关联的计时器。
我希望父类能够启动和停止这些计时器,最重要的是希望父类能够检测到它的哪个子对象“计时器已过”甚至已被引发。
这可能吗?如果可以,最好的方法是什么?
【问题讨论】:
标签: c# winforms multithreading timer
我建议您给子对象一个可以在触发 Timer 时引发的事件。然后,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);
}
}
【讨论】: