8

I want to use a timer only once, at 1 second after the initialization of my main form. I thought the following would have a message box saying "Hello World" just once, but actually a new message box says "Hello World" every one second.

Why so? I had put t.Stop() in the tick event. Also, do I need to dispose the timer somehow to avoid memory leakage?

        Timer t = new Timer();
        t.Interval = 1000;                
        t.Tick += delegate(System.Object o, System.EventArgs e)
                        { MessageBox.Show("Hello World"); t.Stop(); };

        t.Start();   

Please help and show if there is a better way of doing this? Thanks.

3 Answers 3

9

Replace MessageBox.Show("Hello World"); t.Stop(); with t.Stop();MessageBox.Show("Hello World");. Because you're not pressing OK in time, the timer has already ticked again and you never reached the stop code.

Sign up to request clarification or add additional context in comments.

5 Comments

Ok, that works. Thanks. But what's the logic? Why the order matters?
@zaidwaqi: The thread goes into MessageBox.Show method, and doesn't leave until you press OK. But you don't press OK fast enough, and it has already opened a new MessageBox.
Oh :) What about disposing the timer? Is it needed since the timer will not be used anymore?
@zaidwaqi, well you could call t.Dispose() after t.Stop()
@SebastianGodelet As long as he doesn't need it again, he should probably be doing that anyway.
2

Put t.Stop(); before the MessageBox.Show("Hellow World");

Comments

1

You can achieve this also with System.Timers.Timer and setting AutoReset to false. I was looking into which timer to use and prefer this one as it does not require the separate stop command.

using System;
using System.IO;
using System.Timers;

System.Timers.Timer t = new System.Timers.Timer() {
    Interval = 1000,
    AutoReset = false
};

t.Elapsed  += delegate(System.Object o, System.Timers.ElapsedEventArgs e)
    { Console.WriteLine("Hell");}; 
t.Start();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.