wp8.x和Windows 8计时器问题

时间:2014-05-30 04:56:27

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

我正在开发一个简单的测验应用程序,在这里我用组合或计时器显示时间并停止观看。但是计时器不可靠,它会在几秒钟后停止更新,或者在滞后时间内缓慢更新。

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));
    }

上面的代码有什么问题吗?但我没有看到计时器在app中可靠运行。

任何人都遇到过类似的问题。我可以用于UI的任何其他计时器。

由于

2 个答案:

答案 0 :(得分:1)

要在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 :(得分:0)

你可以试试这个。它会以一秒的间隔更新计时器,并且还会更新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);
}