3

How can I run a function, after 10 seconds, after the opening of the program.

This is what I tried, and I'm not able to make it work.

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();
}
johniek_comp
  • 322
  • 3
  • 8

2 Answers2

14

You have a few problems:

  1. You need to use the Load event rather than a button click handler.
  2. You should set the interval to 10000 for a 10 second wait.
  3. You are using a local variable for the timer instance. That makes it hard for you to refer to the timer at a later date. Make the timer instance be a member of the form class instead.
  4. Remember to stop the clock after you run the form, or, it will try to open every 10 seconds

In other words, something like this:

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();
}
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • @balexandre Thanks for your edits. It can be started either with `Start()` or by setting `Enabled` to `true`. I think our edits were getting crossed. – David Heffernan May 19 '12 at 13:34
0

Is will be good for your program something like that?

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");
            }
        }
    }
}
Smit
  • 609
  • 3
  • 11
  • 27
  • your answering with a question? – balexandre May 19 '12 at 13:30
  • Yes. johniek_comp can put function in thread, and start function's logic after 10 seconds of Sleep. – Smit May 19 '12 at 13:33
  • 1
    I wouldn't use Thread.Sleep() for this case, because it will sleep at least 10 seconds. You will not know for sure, when it will be activated again. – basti May 19 '12 at 13:34
  • @chiffre, explain your last statement please. – Smit May 19 '12 at 13:37
  • Activity-changes in multithreading-enviroments are non-deterministic. You will never know for sure, which thread will be running at a certain time. In my opinion it's a sign of poor design, if you replace a job a timer could do with a thread.sleep()-call It's also explained in this [question](http://stackoverflow.com/questions/8844766/problems-with-using-thread-sleep-for-short-times). – basti May 19 '12 at 13:57