0

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?

Callum Watkins
  • 2,844
  • 4
  • 29
  • 49
  • 4
    Subscribe the Tick event only **once**. The way you are doing it now, every time you call toggleCharmsBar() you add yet another event handler and the Tick event handler runs multiple times. Thus making it *look* faster. – Hans Passant Jan 08 '15 at 18:21

1 Answers1

1

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.

Frank Sposaro
  • 8,511
  • 4
  • 43
  • 64
  • 1
    As Hans points out, it's not a new `Timer` instance that's being created. It's simply that a new event handler is being subscribed to the existing `Timer` instance. So the `openTimer_Tick()` event handler method is being called multiple times at each timer tick. – Peter Duniho Jan 08 '15 at 18:25
  • This is a great call, thanks to everyone for helping ;) – Callum Watkins Jan 08 '15 at 19:58