DispatcherTimer 在 C# WPF 中慢慢变快

DispatcherTimer slowly getting faster in C# WPF

似乎导致问题的 DispatcherTimer 是 openTimercloseTimer。第一次启用时,它们以正确的速度工作,但是之后,只要从 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;
    }
}

可能是什么原因造成的?

是否再次调用 ToggleCharmsBar() 方法? 检查以确保您没有分配额外的计时器。 这可能是它看起来更快的原因。实际上,它只是一个处于不同时钟周期的重复计时器。