计时器从不停止
本文关键字:不停止 计时器 | 更新日期: 2023-09-27 18:29:41
我从Tick
回调事件函数调用Stop()
,但它不会停止,该函数会反复运行。为什么以及如何解决此问题?
此函数只调用一次:
System.Windows.Forms.Timer timer1 = new System.Windows.Forms.Timer();
void foo() {
timer1.Interval = 1000;
timer1.Tick += new EventHandler(timerTick);
timer1.Start();
}
以及回调函数:
void timerTick(object o, EventArgs ea)
{
if (browser.ReadyState == WebBrowserReadyState.Complete)
{
MessageBox.Show("stop it!");
timer1.Stop();
}
}
这将显示无限多的stop it
消息框,而它必须显示一次。
您需要反转您的语句:
if (browser.ReadyState == WebBrowserReadyState.Complete)
{
timer1.Stop();
MessageBox.Show("stop it!");
}
就目前情况而言;它会一直滴答作响,直到你关闭一个框(因为MessageBox.Show
块),这可能是一个很多的滴答声。
另一种方法是使用System.Timers.Timer
。你可以告诉计时器运行一次,直到你告诉它才重新启动。
System.Timers.Timer timer1 = new System.Timers.Timer();
void foo() {
timer1.Interval = 1000;
timer1.Elapsed += new ElapsedEventHandler(timerTick);
//This assumes that the class `foo` is in is a System.Forms class. Makes the callback happen on the UI thread.
timer1.SynchronizingObject = this;
//Tells it to not restart when it finishes.
timer1.AutoReset = false;
timer1.Start();
}
void timerTick(object o, ElapsedEventArgs ea)
{
if (browser.ReadyState == WebBrowserReadyState.Complete)
{
MessageBox.Show("stop it!");
}
}