Callum Watkins
Callum Watkins

Reputation: 2991

DispatcherTimer slowly getting faster in C# WPF

The DispatcherTimers that seem to be causing the issue are openTimer and closeTimer. The first time they are enabled they work at the correct speed, however afterwards the speed constantly increases whenever the timer is triggered from within ToggleCharmsBar().

DispatcherTimer openTimer = new DispatcherTimer();
DispatcherTimer closeTimer = new DispatcherTimer();

private void ToggleCharmsBar()
{
    buttonA.IsEnabled = false;
    if (buttonA.Visibility == Visibility.Visible)
    {
        // Close charms bar
        buttonA.Opacity = 1;
        closeTimer.Tick += closeTimer_Tick;
        closeTimer.Interval = TimeSpan.FromMilliseconds(5);
        closeTimer.IsEnabled = true;
    }
    else
    {
        // Open charms bar
        buttonA.Visibility = Visibility.Visible;
        buttonA.Opacity = 0;
        openTimer.Tick += openTimer_Tick;
        openTimer.Interval = TimeSpan.FromMilliseconds(5);
        openTimer.IsEnabled = true;
    }
}

private void closeTimer_Tick(object sender, EventArgs e)
{
    // This timer speeds up with every call to ToggleCharmsBar()
    if (buttonA.Opacity < 0.02)
    {
        buttonA.Opacity = 0;
        buttonA.Visibility = Visibility.Hidden;
        buttonA.IsEnabled = false;
        closeTimer.IsEnabled = false;
    }
    else
    {
        buttonA.Opacity -= 0.02;
    }
}

private void openTimer_Tick(object sender, EventArgs e)
{
    // This timer also speeds up with every call to ToggleCharmsBar()
    if (buttonA.Opacity > 0.98)
    {
        buttonA.Visibility = Visibility.Visible;
        buttonA.Opacity = 1;
        buttonA.IsEnabled = true;
        openTimer.IsEnabled = false;
    }
    else
    {
        buttonA.Opacity += 0.02;
    }
}

What could be causing this?

Upvotes: 0

Views: 1213

Answers (1)

Frank Sposaro
Frank Sposaro

Reputation: 8531

Is the ToggleCharmsBar() method getting call again? Check to make sure you are not assigning an additional timer. This could be the reason that is appears faster. When in reality, it's just a duplicated timer that is on a different clock cycle.

Upvotes: 1

Related Questions