【问题标题】:Timer in C# that fires X seconds after opening program?C# 中的计时器在打开程序后触发 X 秒?
【发布时间】:2012-05-19 13:17:50
【问题描述】:

如何在程序打开 10 秒后运行函数。

这是我尝试过的,但我无法使其工作。

private void button1_Click(object sender, EventArgs e)
{
    Timer tm = new Timer();
    tm.Enabled = true;
    tm.Interval = 60000;
    tm.Tick+=new EventHandler(tm_Tick);
}
private void tm_Tick(object sender, EventArgs e)
{
    Form2 frm = new Form2();
    frm.Show();
    this.Hide();
}

【问题讨论】:

    标签: c# winforms


    【解决方案1】:

    你有几个问题:

    1. 您需要使用Load 事件而不是按钮单击处理程序。
    2. 您应该将间隔设置为 10000 等待 10 秒。
    3. 您正在为计时器实例使用局部变量。这使您以后很难参考计时器。将计时器实例改为表单类的成员。
    4. 请记住在运行表单后停止时钟,否则它将尝试每 10 秒打开一次

    换句话说,是这样的:

    private Timer tm;
    
    private void Form1_Load(object sender, EventArgs e)
    {
        tm = new Timer();
        tm.Interval = 10 * 1000; // 10 seconds
        tm.Tick += new EventHandler(tm_Tick);
        tm.Start();
    }
    
    private void tm_Tick(object sender, EventArgs e)
    {
        tm.Stop(); // so that we only fire the timer message once
    
        Form2 frm = new Form2();
        frm.Show();
        this.Hide();
    }
    

    【讨论】:

    • @balexandre 感谢您的编辑。可以使用Start() 或将Enabled 设置为true 来启动它。我认为我们的编辑被越过了。
    【解决方案2】:

    这样对你的程序有好处吗?

    namespace Timer10Sec
    {
        class Program
        {
            static void Main(string[] args)
            {
                Thread t = new Thread(new ThreadStart(After10Sec));
                t.Start();
            }
    
            public static void After10Sec()
            {
                Thread.Sleep(10000);
                while (true)
                {
                    Console.WriteLine("qwerty");
                }
            }
        }
    }
    

    【讨论】:

    • 您回答了一个问题?
    • 是的。 johniek_comp 可以将函数放入线程中,并在休眠 10 秒后启动函数的逻辑。
    • 我不会在这种情况下使用 Thread.Sleep(),因为它至少会休眠 10 秒。您不确定何时会再次激活。
    • @chiffre,请解释一下你的最后一句话。
    • 多线程环境中的活动变化是不确定的。您永远无法确定,哪个线程将在某个时间运行。在我看来,这是设计不佳的标志,如果你用 thread.sleep()-call 替换计时器可以做的工作,这在question 中也有解释。
    猜你喜欢
    • 2014-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-07
    相关资源
    最近更新 更多