Michael
Michael

Reputation: 57

Speeding up DispatcherTimer when button is clicked

I'm creating a practice application that plays a sound every so often seconds and as a button is pressed it decreases the time interval for the sound to play. For example at the start it plays a sound every 15 seconds and when I press the button it should now play the sound every 10 seconds. Basically every time the user presses the button it decreases the interval by 5 seconds. So I have a DispatcherTimer at the top of my class and created its interval and Tick method when the page loads like such. I also have an int variable for the seconds in the time span.

DispatcherTimer timer = new DispatcherTimer();
int interval = 15;

private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
        timer.Interval = new TimeSpan(0, 0, interval);
        timer.Tick += new EventHandler(timer_Tick);
        timer.Start();
}

void btn_Click(object sender, RoutedEventArgs e)
{
        Button btn = sender as Button;

        interval -= 5;

        timer = new DispatcherTimer();
        timer.Interval = new TimeSpan(0, 0, interval);
}

But this makes the sound play crazily. Is there a proper way to do this?

Upvotes: 1

Views: 437

Answers (2)

VichitraVij
VichitraVij

Reputation: 359

if this is your actual code then Larry is quite right... u have to call timer.stop(); before starting the second. also give some condition so as to disallow interval < 0

Upvotes: 2

Larry Osterman
Larry Osterman

Reputation: 16142

Do you cancel the first dispatcher timer before you start the second? Is it possible that after the first click you have two dispatcher timers firing?

Upvotes: 2

Related Questions