【问题标题】:WPF Dispatchertimer delayed reaction / freezeWPF Dispatchertimer 延迟反应/冻结
【发布时间】:2012-04-16 20:26:03
【问题描述】:

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

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

当我的程序运行时,会有很多延迟/冻结。 例如,时间开始正确计时,但值突然冻结,冻结后时间增加 +3 秒。

我的整个应用程序都出现了这种行为。 使用多个计时器解决此问题的正确方法是什么?

编辑:

我在用 System.Timers 命名空间中的 Timer 替换 DispatcherTimer 时遇到问题。

//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();

错误:“调用线程必须是 STA,因为许多 UI 组件都需要这个。”

最好的问候。

【问题讨论】:

    标签: c# .net wpf


    【解决方案1】:

    DispatcherTimer 在 UI 线程上执行。因此,如果 UI 线程忙碌超过该时间间隔,它将在 UI 线程空闲时执行。 如果你需要更精确的调度,你应该去一段时间而不是在后台运行(System.Threading.Timer、System.Timers.Timer)。但是不要忘记编组。

    hth, 马丁

    【讨论】:

    • 编组究竟是什么意思?以前从未在真正的程序中真正使用过线程。所以我可以用其他类型的计时器完美地替换我的 Dispatcher 计时器功能?
    • 事件将在不同的线程上触发,因此您需要在 UI 线程上执行 UI。这就是编组
    【解决方案2】:

    我猜这是因为它们都在同一个线程上运行。

    【讨论】:

    【解决方案3】:

    使用 System.Threading.Timer 并在更新 UI 时使用 SyncronizationContext.Syncronize 来运行更新代码。

    不要忘记从 UI 线程上的 SyncronizationContext.Current 获取上下文。

    【讨论】:

    • 想多说明一点?谢谢。 System.Timer 的语法看起来更像 Dispatcher 而不是 Threading timer。
    猜你喜欢
    • 2019-06-07
    • 1970-01-01
    • 2023-03-03
    • 2023-01-31
    • 2019-08-27
    • 1970-01-01
    • 2016-01-10
    • 1970-01-01
    • 2015-06-16
    相关资源
    最近更新 更多