WPF Dispatchertimer延迟反应/冻结反应、WPF、Dispatchertimer

2023-09-06 04:53:13 作者:岛田家族没有推车

在我的WPF应用程序,我用3个不同的DispatcherTimers。

一个用于显示当前时间 一类是适用于运行一个数据库查询每5秒 第三个刷新一个值的自定义按钮,每1秒

当我的程序运行时有很多的延迟/冻结。 例如,时间开始正确地滴答作响,但在突然的价值冻结和冻结后的时间得到+3秒例如递增。

我收到了我的整个应用程序的这种行为。 什么是正确的方式来解决这个问题,几个定时器?

编辑:

我有问题与来自System.Timers命名一个计时器更换DispatcherTimer。

  //新的code与计时器
timerW =新的Timer();
        timerW.Elapsed + =新ElapsedEventHandler(timerWegingen_Tick);
        timerW.Interval = 5000;
        timerW.Start();

        // OLD工作code
        timerW =新DispatcherTimer();
        timerW.Tick + =新的EventHandler(timerWegingen_Tick);
        timerW.Interval =新的时间跨度(0,0,5);
        timerW.Start();
 
C Timer使用 WPF Winform

错误:调用线程必须为STA,因为许多UI组件都需要这种的

最好的问候。

解决方案

在DispatcherTimer是在UI线程上执行。所以如果UI线程繁忙以上的时间间隔,将执行时的UI线程是自由地这样做。 如果您需要更多precise调度,你应该去的时间比在后台运行(System.Threading.Timer,System.Timers.Timer的)。但不要忘了编组呢。

心连心, 马丁

In my WPF application i use 3 different DispatcherTimers.

One is for displaying the current time One is are for running a DB query every 5 sec The third one refreshes a value for a custom button every 1 sec

When my program is running there are a lot of delays / freezes. For example the time starts ticking correctly but on a sudden the value freezes up and after the freeze the time gets incremented by +3 seconds for example.

I am getting this behavior over my entire application. What is the proper way to solve this problem with several timers?

EDIT:

I am having problems to replace a DispatcherTimer with a Timer from System.Timers namespace.

//new code with timer
timerW = new Timer();
        timerW.Elapsed += new ElapsedEventHandler(timerWegingen_Tick);
        timerW.Interval = 5000; 
        timerW.Start();

        //OLD Working Code
        timerW = new DispatcherTimer();
        timerW.Tick += new EventHandler(timerWegingen_Tick);
        timerW.Interval = new TimeSpan(0, 0,5);
        timerW.Start();

Error : "The calling thread must be STA, because many UI components require this."

Best regards.

解决方案

the DispatcherTimer is executed on the UI thread. So if the UI thread is busy for more than the interval, it will be executed when the UI thread is free to do so. If you need more precise scheduling, you should go for a time than runs in the background (System.Threading.Timer, System.Timers.Timer). But don't forget about marshalling then.

hth, Martin