计时器不会停止c#

时间:2013-11-02 10:39:25

标签: c# timer

当用户按下按钮时,我在表单中使用计时器每隔3秒向控制器发送一个命令。用户再次按下相同按钮后,计时器应停止。但在我的情况下,计时器不会停止。我正在以下列方式使用计时器。

private void autoModeTempBtn_Click(object sender, EventArgs e)
    {
        System.Timers.Timer tempTimer = new System.Timers.Timer(3000);
        tempTimer.SynchronizingObject = this;
        tempTimer.AutoReset = true;

        if (autoModeTempBtn.Text == "Get Temperature Auto Mode")
        {
            autoModeTempBtn.Text = "hello";

            tempTimer.Elapsed += new System.Timers.ElapsedEventHandler(OnTemperatureEvent);
            tempTimer.Enabled = true;
        }
        else /*user presses button second time */
        {
            tempTimer.Stop();
            tempTimer.AutoReset = false;
            tempTimer.Enabled = false;
            autoModeTempBtn.Text = "Get Temperature Auto Mode";
        }
    }
    private void OnTemperatureEvent(object source, System.Timers.ElapsedEventArgs e)
    {
       //do something
    }

我在哪里弄错了?

1 个答案:

答案 0 :(得分:3)

每次单击按钮时,都会创建新的计时器。创建计时器一次,只需单击就可以启动/停止计时器。另外,您应该使用System.Windows.Forms.Timer代替System.Timers.Timer

var _timer = new Timer() { Interval = 3000 };

private void autoModeTempBtn_Click(object sender, EventArgs e)
{
    if (!validateSerialNumber())
        return;

    if (!_timer.Enabled)
    {
        _timer.Start();
        autoModeTempBtn.Text = "hello";
    }
    else
    {
        _timer.Stop();
        autoModeTempBtn.Text = "Get Temperature Auto Mode";
    }
}

并将此代码添加到构造函数中:

_timer.Tick += OnTemperatureEvent;