DispatcherTimer apply interval and execute immediately

Initially set the interval to zero and then raise it on a subsequent call.

void timer_Tick(object sender, EventArgs e)
{
    ((Timer)sender).Interval = new TimeSpan(0, 0, 5);
    MessageBox.Show("!!!");
}

There are definitely more elegant solutions, but a hacky way is to just call the timer_Tick method after you set the interval initially. That'd be better than setting the interval on every tick.


could try this:

timer.Tick += Timer_Tick;
timer.Interval = 0;
timer.Start();

//...

public void Timer_Tick(object sender, EventArgs e)
{
  if (timer.Interval == 0) {
    timer.Stop();
    timer.Interval = SOME_INTERVAL;
    timer.Start();
    return;
  }

  //your timer action code here
}

Another way could be to use two event handlers (to avoid checking an "if" at every tick):

timer.Tick += Timer_TickInit;
timer.Interval = 0;
timer.Start();

//...

public void Timer_TickInit(object sender, EventArgs e)
{
    timer.Stop();
    timer.Interval = SOME_INTERVAL;
    timer.Tick += Timer_Tick();
    timer.Start();
}

public void Timer_Tick(object sender, EventArgs e)
{
  //your timer action code here
}

However the cleaner way is what was already suggested:

timer.Tick += Timer_Tick;
timer.Interval = SOME_INTERVAL;
SomeAction();
timer.Start();

//...

public void Timer_Tick(object sender, EventArgs e)
{
  SomeAction();
}

public void SomeAction(){
  //...
}

Tags:

C#

.Net

Timer