【问题标题】:Timer cannot be stopped in C#定时器不能在 C# 中停止
【发布时间】:2009-02-26 11:26:09
【问题描述】:

我在 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() 之后,我仍会继续在屏幕上接收 MessageBox。当我按 esc 时,它停止了。但是,我预计只会出现一个消息框......我还应该做什么?添加 timer1.Enabled = false 不会改变行为。

谢谢

【问题讨论】:

  • 当前代码是具有所需行为的代码。

标签: c# .net winforms timer


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

    timer1_Tick 可能正在后台线程上执行。 UI 调用(例如 MessageBox.Show() 和后台线程不能混合使用。

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

    【讨论】:

      【解决方案3】:

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

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多