Windows窗体计时器不会停止。怎么可能? [英] Windows Forms Timer doesn't stop. How is that possible?

查看:162
本文介绍了Windows窗体计时器不会停止。怎么可能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在调试期间,我可以看到在执行 Timer.Stop()之后,Timer.Enabled = false执行命令,Timer仍然运行(Timer.Enabled = true)。怎么可能?

During debugging I can see that after Timer.Stop() or Timer.Enabled = false commands are executed, Timer is still running (Timer.Enabled = true). How is that possible?

推荐答案

当您在工作线程上停止定时器时,这是可能的。例如:

This is possible when you stop the timer on a worker thread. For example:

public partial class Form1 : Form {
    public Form1() {
        InitializeComponent();
    }
    Timer timer1;
    protected override void OnLoad(EventArgs e) {
        base.OnLoad(e);
        timer1 = new Timer();
        timer1.Interval = 3000;
        timer1.Start();
        var t = new System.Threading.Thread(stopTimer);
        t.Start();
    }
    private void stopTimer() {
        timer1.Enabled = false;
        System.Diagnostics.Debug.WriteLine(timer1.Enabled.ToString());
    }
}

输出:

True

Output:
True

定时器必须由UI线程停止,该类自动处理。非常类似于Control.BeginInvoke()。有一个明确的比赛,Tick事件处理程序可以在您停止后运行。如果您创建的第一个计时器是在工作线程上创建的,那么这也可能发生在UI线程上。例如闪屏。这不健康,你应该解决这个问题。

The timer must be stopped by the UI thread, the class takes care of it automatically. Quite similar to Control.BeginInvoke(). There's an explicit race, the Tick event handler can run after you stopped it. This can also happen on the UI thread if the very first timer you create is created on a worker thread. A splash screen for example. That's not healthy, you ought to fix that.

这篇关于Windows窗体计时器不会停止。怎么可能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆