【问题标题】:Update UI element from thread从线程更新 UI 元素
【发布时间】:2014-06-07 20:42:31
【问题描述】:

我尝试在 Windows Phone 中创建每 10-15 毫秒更新一次的计时器(对于 UI 元素)。我希望有机会追加时间。所以我创建了 TimeSpan 和 DispatcherTimer,其中间隔 = 15 ms。因此,每 15 毫秒调用一次事件,其中我将 15 毫秒减去 timeSpan 并且当时间跨度

【问题讨论】:

  • 你为什么使用 15 毫秒的间隔而不是你想要等待的全部时间(如果我理解正确的话是 4 秒)?在 UI 线程中调用需要一些时间,所以我想这就是导致延迟/不准确的原因。此外,使用 async/await 应该可以工作。
  • 我每 15 毫秒为用户更新一次。它看起来不错。所以我使用 async await async Task<bool> calculateTime() { timeRemaining -= TimeSpan.FromMilliseconds(tic);}async void timer_Tick(object sender, EventArgs e) {var a = await calculateTime();}
  • 其中 tic = 15 timeRemaining = 4000
  • 您能否将代码放入问题中,因为格式会更好。此外,计算时间似乎没有返回 bool 或 Task?还有一个问题:你每 15 毫秒更新什么 - 一些 UI?

标签: c# windows-phone-8 windows-phone


【解决方案1】:
So every 15 ms call the event where i subtract 15 ms to timeSpan and when timespan <= 0 i call some method.

你的逻辑有问题。您不可能以这种方式更新您的时间跨度,因为:

  1. 正如 Stephen Cleary 在他的回答中提到的,你不能保证计时器会在 15 毫秒时触发
  2. 即使这样做了,它也没有考虑实际更新时间跨度所需的时间(假设计算新的时间跨度需要 1 毫秒,您的计时器将每 15 毫秒漂移 1 毫秒)

要获得准确的时间,您需要存储开始时间的时间戳(使用 DateTime.UtcNow 检索它。每次计时器滴答时,获取新的时间戳并减去您保存的时间戳。这样,您确切地知道已经过去了多少时间,并且您的计时器永远不会漂移。

private DateTime start; // Set this with DateTime.UtcNow when starting the timer

void timer_Tick(object sender, EventArgs e)
{
    // Compute the new timespan
    var timespan = DateTime.UtcNow - start;

    // Do whatever with it (check if it's greater than 4 seconds, display it, ...)
}

【讨论】:

  • 哦,我是傻瓜(:非常感谢
【解决方案2】:

所以每 15 毫秒调用一次事件,我将时间跨度减去 15 毫秒

还有你的问题。

当您在任何 Windows 平台上设置计时器时,您都不能期望很高的精度。在桌面上,我相信消费类硬件上的正常调度周期约为 12 毫秒(当然其他应用程序可以大大减少它)。我不知道手机上的日程安排是什么样的,但我认为它不如台式机准确(出于电池寿命的原因)。

因此,您根本无法在 Windows 上以这种方式解决此问题,因为您不能假设计时器每 15 毫秒触发一次。相反,只需将 DispatcherTimer 启动到您需要的完整时间跨度,例如 4 秒。

【讨论】:

    【解决方案3】:

    试试这个来更新你的计时器线程中的 UI 元素

     Dispatcher.BeginInvoke(() =>
            {
                //Update Your Element.
            });
    

    【讨论】:

    • BeginInvoke 有效,但时间多于生命中的时间
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-21
    • 1970-01-01
    相关资源
    最近更新 更多