Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DispatcherTimer apply interval and execute immediately

Tags:

c#

.net

timer

Basically when we apply some interval ie 5 sec we have to wait for it.

Is it possible to apply interval and execute timer immediately and don't wait 5 sec? (I mean the interval time).

Any clue?

Thanks!!

public partial class MainWindow : Window
    {
        DispatcherTimer timer = new DispatcherTimer();

        public MainWindow()
        {
            InitializeComponent();

            timer.Tick += new EventHandler(timer_Tick);
            this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
        }

        void timer_Tick(object sender, EventArgs e)
        {
            MessageBox.Show("!!!");
        }

        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            timer.Interval = new TimeSpan(0, 0, 5);
            timer.Start();
        }
    }
like image 456
Friend Avatar asked Jul 03 '12 17:07

Friend


2 Answers

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(){
  //...
}
like image 83
George Birbilis Avatar answered Oct 07 '22 17:10

George Birbilis


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("!!!");
}
like image 33
Austin Salonen Avatar answered Oct 07 '22 19:10

Austin Salonen