Reputation: 1843
I am working on a simple quiz app, where I am showing time elapsed with combination or timer and stop watch. But timer is not reliable, it stop updating after couple of seconds or update slow with lag in time.
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));
}
Is there anything wrong with above code. But I don't see timer working reliably in app.
Anyone faced similar problem. Is any other timer I can use for UI.
Thanks
Upvotes: 0
Views: 645
Reputation: 11228
To update the UI in Windows Runtime you should use DispatcherTimer
- it ticks on the UI thread:
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();
}
Upvotes: 1
Reputation: 2621
You can try this. It would update timer at interval of One Second and also Update the 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);
}
Upvotes: 0