DispatcherTimer applies the interval and immediately executes

Basically, when we apply a certain interval, i.e. 5 seconds, we must wait for him.

Is it possible to immediately apply the interval and execute the timer and not wait 5 seconds? (I mean the time interval).

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(); } } 
+8
c # timer
source share
3 answers

First 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("!!!"); } 
+7
source share

There are definitely more elegant solutions, but the hacker way is to simply call the timer_Tick method after you set the interval initially. This would be better than setting the interval at each tick.

+13
source share

may try the following:

 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 an "if" check on 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, a cleaner way is what has already been suggested:

 timer.Tick += Timer_Tick; timer.Interval = SOME_INTERVAL; SomeAction(); timer.Start(); //... public void Timer_Tick(object sender, EventArgs e) { SomeAction(); } public void SomeAction(){ //... } 
+2
source share

All Articles