0

当用户按下按钮时,我每 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
    }

我在哪里犯错?

4

1 回答 1

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;
于 2013-11-02T10:46:44.267 回答