【发布时间】:2014-05-30 17:29:29
【问题描述】:
我正在开发一个简单的测验应用程序,我在其中使用组合或计时器和秒表显示经过的时间。但是定时器并不可靠,它会在几秒钟后停止更新,或者更新缓慢并延迟。
private void StartChallenge()
{
LoadQuestion();
System.Threading.Timer t = new System.Threading.Timer(new System.Threading.TimerCallback(updateTime), null, 0, 1000); //start timer immediately and keep updating it after a second
stopWatch = new System.Diagnostics.Stopwatch();
stopWatch.Start();
}
private async void updateTime(object state)
{
TimeSpan ts = stopWatch.Elapsed;
await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => txtTimeElapsed.Text = String.Format("{0:00}:{1:00}:{2:00} elapsed", ts.Hours, ts.Minutes, ts.Seconds));
}
上面的代码有什么问题吗?但我没有看到计时器在应用程序中可靠地工作。
任何人都遇到过类似的问题。是否还有其他可以用于 UI 的计时器。
谢谢
【问题讨论】:
-
尝试将 this.Dispatcher.RunAsync() 保存到局部变量中,等待该变量并检查任务中是否有异常属性。
-
计时器正在收集垃圾。您需要在类的字段中存储对它的引用,局部变量不够好。
-
所以你的意思是说 Timer t 应该是一个类变量?
标签: c# windows-phone-8 windows-8 windows-8.1 windows-phone-8.1