繁体   English   中英

为什么不按时发生DispatcherTimer Tick事件?

[英]Why is a DispatcherTimer Tick event not occurring on time?

我想禁用一个按钮-防止双击:在平板电脑上按一次,单击两次,这是我所知道的最简单的黑客技术-在很短的时间内,但我发现/调试的间隔实际上可能太长了; 50毫秒vs> 2秒。

只有一行可以启动计时器,而只有一行可以停止计时器。 随机间隔是50毫秒或更大。 没有CPU消耗,我只需在4核台式机上用鼠标单击该按钮即可。

请问是什么原因?

    DispatcherTimer timerTouchDelay = new DispatcherTimer();

    protected override void OnMouseDown(MouseButtonEventArgs e)
    {
        //Init
        if (timerTouchDelay.Interval.Milliseconds == 0)
        {
            timerTouchDelay.Tick += new EventHandler(timerTouchDelay_Tick);
            timerTouchDelay.Interval = new TimeSpan(0, 0, 0, 0, 50); //ms

        }


        if(timerTouchDelay.IsEnabled)
            return;

        timerTouchDelay.Start();

        HandleKeyDown();
        base.OnMouseDown(e);
    }

    private void timerTouchDelay_Tick(object sender, EventArgs e)
    {
        timerTouchDelay.Stop();
    }

要理解为什么会这样,我强烈建议以下文章:

在.NET Framework类库中比较计时器类

作为参考, DispatcherTimerSystem.Windows.Forms.Timer非常相似,为此作者声明“如果您正在寻找节拍器,那么您来错了地方”。 此计时器的设计目的不是精确间隔“滴答”。

为什么不运行计时器,而不是只记录最后一次按下按钮的时间呢? 如果已超过50毫秒,请继续执行操作,否则请退出。

DateTime lastMouseDown = DateTime.MinValue;

protected override void OnMouseDown(MouseButtonEventArgs e)
{
    if(DateTime.Now.Subtract(lastMouseDown).TotalMilliseconds < 50)
       return;
    lastMouseDown = DateTime.Now;

    HandleKeyDown();
    base.OnMouseDown(e);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM