简体   繁体   中英

How to let System.Windows.Forms.Timer to run the Tick handler immediately when starting?

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?

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

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

eg

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM