C#中的计时器,程序打开X秒后触发?

3

如何在程序打开后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();
}
2个回答

14

你有几个问题:

  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”来启动。我想我们的编辑有些冲突了。 - David Heffernan

0

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

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");
            }
        }
    }
}

你回答问题时有疑问吗? - balexandre
是的,johniek_comp可以将函数放入线程中,在10秒的休眠后启动函数的逻辑。 - Smit
1
我不会在这种情况下使用Thread.Sleep(),因为它会至少休眠10秒。你无法确定它何时会再次被激活。 - basti
@chiffre,请解释一下你最后的陈述。 - Smit
多线程环境中的活动变化是不确定的。你永远不会确定哪个线程在某个时间运行。在我看来,如果你用 thread.sleep() 调用替换了定时器可以完成的工作,那么这是设计不良的标志。这也在这个问题中有所解释:https://dev59.com/IF_Va4cB1Zd3GeqPRTtS。 - basti

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接