简单DispatchTimer标记仅在Win10中是不稳定的WPF

问题描述 投票:0回答:1

我已经在Win7和Win10上尝试过此方法。如我所想,在Win7上工作时,每100毫秒调用一次Tick。但是在win10上,滴答声在运行时被调用了2次,然后停止,直到我将鼠标悬停在该应用程序上为止,该程序会触发另一个滴答声。这很奇怪。

我正在使用System.Windows.Threading。

代码都在代码后方进行测试,而这一切都是为了使其简单:

public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            TimerGeneral(true);
        }

        public DispatcherTimer timer = new DispatcherTimer();
        int s;

        public void TimerGeneral(bool estado)
        {
            timer.Interval = TimeSpan.FromMilliseconds(100);

            if (estado && !timer.IsEnabled) { timer.Tick += timer_Tick; timer.Start(); }

            else if (!estado && timer.IsEnabled) { timer.Stop(); }

        }

        public void timer_Tick(object sender, EventArgs e)
        {
            Debug.WriteLine("tick" + s++);
        }
    }

对Win10为何有所不同,我有点迷惑,对不起。

wpf timer windows-7 windows-10
1个回答
0
投票

请记住,当使用默认构造函数实例化DispatcherTimer时(如您所做的那样),计时器的Dispatcher默认情况下将以DispatcherPriority.Background执行!因此,高延迟。

通过使用适当的构造函数指定更高的优先级:

var dispatcherTimer = new DispatcherTimer(DispatcherPriority.Normal, Application.Current.Dispatcher) 

这应该可以解决您的问题。如果延迟仍然太高,请尝试DispatcherPriority.Send(小心使用)。如果将操作发布到Dispatcher处的DispatcherPriority.Send,则该操作将绕过队列并立即执行。

取决于计时器间隔和工作量,DispatcherPriority应该尽可能低,以防止UI变慢。

或者,如果DispatcherPriority或任何其他计时器对您来说效果更好,则只需使用它。您可以使用Timers.TimerApplication.Current.Dispatcher.Invoke(Action)执行与UI相关的代码。

© www.soinside.com 2019 - 2024. All rights reserved.