I've recently started to delve into the world of windows phone 8 dev, and as a learning experience I've decided to make a stopwatch application. Now, given I've been a web guy most of my career, I've never come across UI thread locking issues, so the solution I've come up with to ensure my stopwatch class is updating the UI thread 'correctly' is (in my opinion at least) in need of a review.
So my overall questions with the below code are;
Am I doing it "right"? I realise that can be kind of broad; I just want to make sure I'm not committing any cardinal sins of UI development.
Are there simpler approaches to what I've done?
Are there any improvements to the code that someone would suggest? I'm not sure using thread.sleep is a good idea, but when I take it out, it ends up locking the UI thread again. Hence why I'm asking for input.
My StopWatch Class:
public class StopwatchClass : IDisposable
{
DispatcherTimer _timer;
public int Interval { get; set; }
public int Seconds { get; set; }
public int Minutes { get; set; }
public int Hours { get; set; }
public bool IsRunning { get { return _timer.IsEnabled; } }
public TimeSpan Elapsed { get; set; }
public List<TimeSpan> Splits { get; set; }
public StopwatchClass(int interval)
{
this.Splits = new List<TimeSpan>();
_timer = new DispatcherTimer();
_timer.Interval = new TimeSpan(0, 0, interval);
_timer.Tick += timer_Tick;
}
void timer_Tick(object sender, EventArgs e)
{
this.Seconds += 1;
if (this.Seconds == 60)
{
this.Minutes += 1;
this.Seconds = 0;
}
if (this.Minutes == 60)
{
this.Hours += 1;
this.Minutes = 0;
}
}
public void Start()
{
_timer.Start();
}
public void Stop()
{
_timer.Stop();
}
public void Reset()
{
_timer = new DispatcherTimer();
this.Seconds = 0;
this.Minutes = 0;
this.Hours = 0;
this.Splits.Clear();
}
public void Split()
{
var timeSpan = new TimeSpan(this.Hours, this.Minutes, this.Seconds);
this.Splits.Add(timeSpan);
}
public void Dispose()
{
_timer.Tick -= timer_Tick;
}
}
And the WP8 button code (secondsValue is a text block on the wp8 page).
private async void startStopwatch_Click(object sender, RoutedEventArgs e)
{
watch.Start();
await Task.Factory.StartNew(() =>
{
while (watch.IsRunning)
{
Thread.Sleep(1000);
Dispatcher.BeginInvoke(() => secondsValue.Text = watch.Seconds.ToString());
}
});
}