call Tick event when timer starts [duplicate]

2019-01-25 19:05发布

This question already has an answer here:

I'm using 'System.Windows.Forms.Timer' to repeat a task. But when the timer starts, I have to wait for one interval before the task starts. The interval is set to 10 seconds to give the task enough time to do it's thing. But there is an 'awkward silence' waiting for it to start the first time. Is there a way to trigger the Tick event when the timer is enabled? (I am unable to use threading, callbacks or events to get the task repeat)

    private int counter;
    Timer t = new Timer();

    private void InitializeTimer()
    {
        counter = 0;
        t.Interval = 750;
        t.Enabled = true;

        t.Tick += new EventHandler(timer1_Tick);
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        if (counter >= 3)
        {
            t.Enabled = false;                
        }
        else
        {
            //do something here
            counter++;
        }
    }

标签: c# timer
4条回答
Melony?
2楼-- · 2019-01-25 19:10

The simplest way might be to initially set the Interval to something very small, then increase it in the Tick handler, or in a separate handler.

This will ensure the first "tick" occurs in the same manner as subsequent ticks, e.g. on its own thread, rather than in the context of the initialize method.

查看更多
祖国的老花朵
3楼-- · 2019-01-25 19:19

Just create a method then call this from within your timer and also just before you start your timer.

private int counter; 
Timer t = new Timer(); 

private void InitializeTimer() 
{ 
    counter = 0; 
    t.Interval = 750; 

    DoMything();
    t.Tick += new EventHandler(timer1_Tick); 
    t.Enabled = true; 
} 

private void timer1_Tick(object sender, EventArgs e) 
{ 
    if (counter >= 3) 
    { 
        t.Enabled = false;                 
    } 
    else 
    { 
        //do something here 
        counter++; 
        DoMything();
    } 
} 


private void DoMything()
{
   //Do you stuff here
}
查看更多
ゆ 、 Hurt°
4楼-- · 2019-01-25 19:27

You can always call your method manually:

private void InitializeTimer()
{
    counter = 0;
    t.Interval = 750;
    t.Enabled = true;
    timer1_Tick(null, null);

    t.Tick += new EventHandler(timer1_Tick);
}
查看更多
疯言疯语
5楼-- · 2019-01-25 19:28

You could use a System.Threading.Timer.

This has a constructor that takes an initial wait period. Set this to zero and the timer will trigger the callback immediately then every interval you specify thereafter.

Timer stateTimer = new Timer(tcb, autoEvent, 0, 750);
查看更多
登录 后发表回答