无法在C#中停止定时器

时间:2009-02-26 11:26:09

标签: c# .net winforms timer

我在Windows窗体(C#3.0,.net 3.5 SP1,VS2008 SP1,Vista)上有一个计时器,即使在它被停止后似乎也能正常工作。代码是:

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不会改变行为。

由于

3 个答案:

答案 0 :(得分:5)

我可能错了,但是MessageBox.Show()是一个阻塞操作(等待你关闭对话框)?如果是这样,只需将Show()调用移到Stop / Enabled行之后?

答案 1 :(得分:1)

这里可能有几个因素在起作用。

模态MessageBox.Show()可以防止计时器停止生效,直到它被解除(正如Brian指出的那样)。

timer1_Tick可能正在后台线程上执行。

表示MessageBox.Show()和后台线程等UI调用

使用BeginInvoke调用显示消息框的方法可以解决这两个问题。

答案 2 :(得分:1)

请注意,以下是不必要的:

            timer1.Stop();
            timer1.Enabled = false;

Stop()Enabled=false相同。 Start()Enabled=true相同。

http://msdn.microsoft.com/en-us/library/system.windows.forms.timer.enabled.aspx