wp8.X和Windows 8定时器问题

本文关键字:定时器 问题 Windows wp8 | 更新日期: 2023-09-27 18:06:04

我正在做一个简单的测验应用程序,在那里我显示时间流逝的组合或计时器和秒表。但是timer是不可靠的,它会在几秒钟后停止更新,或者更新缓慢,有时间延迟。

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。

谢谢

wp8.X和Windows 8定时器问题

要在Windows运行时更新UI,您应该使用DispatcherTimer -它在UI线程上滴答:

http://msdn.microsoft.com/en-us/library/windows/apps/xaml/windows.ui.xaml.dispatchertimer.aspx

Stopwatch sw;
DispatcherTimer timer;
public MainPage()
{
    this.InitializeComponent();
    this.NavigationCacheMode = NavigationCacheMode.Required;
    sw = new Stopwatch();
    timer = new DispatcherTimer();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
    sw.Start();
    timer.Interval = TimeSpan.FromSeconds(1);
    timer.Tick += (i, j) => { txtBlock.Text = sw.Elapsed.ToString(); };
    timer.Start();    
}

你可以试试这个。它将以1秒的间隔更新计时器并更新TimerTextBlock

public void LoadTimer()
{
    int sec = 0;
    Timer timer = new Timer((obj) =>
    {
        Dispatcher pageDispatcher = obj as Dispatcher;
        pageDispatcher.BeginInvoke(() =>
        {
            sec++;
            TimerTextBlock.Text = sec.ToString();
        });
    }, this.Dispatcher, 1000, 1000);
}