Search code examples
c#wpfxamldispatchertimer

Call event in dispatchtimer after every one minute interval


I created a dispatcher timer with one minute interval,

DispatcherTimer dispatcherTimer = new DispatcherTimer();//creation of dispatchtimer

private void btnstart_Click(object sender, RoutedEventArgs e)
{
    dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
    dispatcherTimer.Start();
    dispatcherTimer.Interval = TimeSpan.FromMinutes(1);
}

When button click the timer start and I created event in it.Every one minute interval it will call the event.

private void dispatcherTimer_Tick(object sender, EventArgs e)
{
    if (dispatcherTimer.Interval == TimeSpan.FromMinutes(1))
    {
        //...
        //...
    }
}

But, My problem is when I click start button it go to event (dispatcherTimer_Tick) after 60 seconds it need to go for that event and after every 1minute interval it will call that event it's working correctly. Initially when I click start button it suddenly call that event but I want after 60seconds (ie after 1 minute) need to call that dispatcherTimer_Tick event.


Solution

  • Your problem is that your code doing:

    //...
    dispatcherTimer.Start();
    dispatcherTimer.Interval = TimeSpan.FromMinutes(1);
    //...
    

    instead of:

    //...
    dispatcherTimer.Interval = TimeSpan.FromMinutes(1);
    dispatcherTimer.Start();
    //...  
    

    Set the dispatcherTimer.Interval before calling Start().