定时器不能在 C# 中停止 [英] Timer cannot be stopped in C#
问题描述
我在 Windows 窗体(C# 3.0、.net 3.5 SP1、VS2008 SP1、Vista)上有一个计时器,即使在它停止后似乎也能工作.代码是:
I have a timer on a windows form (C# 3.0, .net 3.5 SP1, VS2008 SP1, Vista) that seems to work even after it is stoppped. The code is:
using System;
using System.Windows.Forms;
namespace TestTimer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
StartTimer();
}
private DateTime deadline;
private void StartTimer()
{
deadline = DateTime.Now.AddSeconds(4);
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
int secondsRemaining = (deadline - DateTime.Now).Seconds;
if (secondsRemaining <= 0)
{
timer1.Stop();
timer1.Enabled = false;
MessageBox.Show("too slow...");
}
else
{
label1.Text = "Remaining: " + secondsRemaining.ToString() + (secondsRemaining > 1 ? " seconds" : " second");
}
}
}
}
即使在 timer1.Stop() 被调用之后,我仍然在屏幕上接收到 MessageBoxes.当我按 esc 时,它会停止.然而,我预计只会出现一个消息框......我还应该做什么?添加 timer1.Enabled = false 不会改变行为.
Even after the timer1.Stop() is called, I keep reeciving MessageBoxes on the screen. When I press esc, it stops. Howevere, I've expected that only one message box appears... What else should I do? adding timer1.Enabled = false does not change the behavior.
谢谢
推荐答案
我可能错了,但是 MessageBox.Show() 是阻塞操作(等待您关闭对话框)吗?如果是这样,只需将 Show() 调用移动到停止/启用行之后?
I could be wrong, but is MessageBox.Show() a blocking operation (that waits for you to dismiss the dialog)? If so, just move the Show() call to after the Stop/Enabled lines?
这篇关于定时器不能在 C# 中停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!