【发布时间】:2015-01-21 09:45:16
【问题描述】:
我在用户控件中结束计时器操作时遇到问题。我通过一些操作创建了用户控件,使用 Timer 间隔发生。我想实现这个目标:
当用户使用我的用户控件关闭窗口时,操作(在 Calculate() 方法中)停止。这是我在MyUserControl.cs 中的代码:
// fields
private Timer timer;
// ctor
public TestUserControl()
{
InitializeComponent();
timer = new Timer();
timer.Tick += timer_Tick;
timer.Interval = 5000;
timer.Start();
}
void timer_Tick(object sender, EventArgs e)
{
Compute();
}
void ParentForm_FormClosing(object sender, FormClosingEventArgs e)
{
timer.Stop();
}
private static void Compute()
{
// do something
}
而TestUserControl.Control.Desinger.cs 中InitializeComponent() 方法中的这一行:
this.ParentForm.FormClosing += new System.Windows.Forms.FormClosingEventHandler(ParentForm_FormClosing);
但我在这一行中遇到异常:“System.NullReferenceException”类型的未处理异常
【问题讨论】:
-
您为什么需要这样做?...当包含您的 UserControl 的表单关闭时,您的 Timer 将停止,并且 UserControl 与形式。现在,如果 Compute() 恰好在 Form 关闭时正在运行,那么它将在 Form 开始关闭过程之前完成(除非您使用 DoEvents 做了一些时髦的事情)。如果您需要 Compute() 过早停止,则必须修改该代码以定期检查某种“关闭”标志,以便它可以退出并允许表单继续正常关闭。
-
我正在做一些数据库操作,每隔一段时间更新一次数据网格。我想在表单关闭时结束这个操作。
-
@Idle_Mind: “当包含你的 UserControl 的表单关闭时,你的 Timer 将被停止”——这不适用于
Timer实例,就像这里的情况一样,明确声明并初始化,而不是通过设计器添加到控件中。 -
@PeterDuniho,你是对的;很好的收获。