6

The Timer following is System.Windows.Forms.Timer C# Code:

Timer myTimer = new Timer();
myTimer.Interval = 10000;
myTimer.Tick += new EventHandler(doSth);
myTimer.Start();

The timer will doSth every 10 seconds, but how to let it doSth immediately when starting?

I tried to create a custom timer which extends Timer, but I can't override the Start method.

For now, my code is:

myTimer.Start();
doSth(this, null);

I don't think it's good. How to improve it?

Freewind
  • 193,756
  • 157
  • 432
  • 708
  • 1
    I think it's good. See http://stackoverflow.com/questions/6924072/how-to-fire-timer-elapsed-event-immediatly also. – Otiel Aug 08 '12 at 14:10
  • 1
    Freewind, you can change this myTimer.Tick += new EventHandler(doSth); look at the answer and example below that I've posted *** there is no need to pass any sender its get call when interval time ends. – MethodMan Aug 08 '12 at 14:16

3 Answers3

17

It's perfect. Don't change a thing.

Ben
  • 34,935
  • 6
  • 74
  • 113
3

I'm not sure of your exact requirements but why not put the code inside your timer callback inside another method?

e.g.

private void tmrOneSec_Tick(object sender, System.EventArgs e)
{
    DoTimerStuff();
}

private void DoTimerStuff()
{
    //put the code that was in your timer callback here
}

So that way you can just call DoTimerStuff() when your application starts up.

gcb
  • 366
  • 5
  • 16
1

The timer has to have form level scope, and it's not clear that you have that. I whipped up a small example out of curiosity and it is working for me:

    private void Form1_Load(object sender, EventArgs e)
    {
        txtLookup.Text = "test";
        DoSomething();
        timer1.Start();
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        DoSomething();
    }

    private void DoSomething()
    {
        txtLookup.Text += "ticking";
    }

Every 10 seconds it appends another "ticking" to the text in the textbox.

You say,

"The timer will doSth every 10 seconds, but how to let it doSth immediately when starting?"

I say, call doSth immediately before calling the timer's start method

GrayFox374
  • 1,742
  • 9
  • 13