private DispatcherTimer stopwatch;
private uint stopwatch_count;
stopwatch_count = 0;
stopwatch = new DispatcherTimer();
stopwatch.Interval = new TimeSpan(0, 0, 1);
stopwatch.Tick += ClockTick;


private void ClockTick(object sender, object e)
{
    stopwatch_count++;
    uint hours = stopwatch_count / 3600;
    uint seconds = stopwatch_count % 3600;
    uint minutes = seconds / 60;
    seconds = seconds % 60;
    value.Text = hours.ToString("D2") + ":" + minutes.ToString("D2") + ":" + seconds.ToString("D2");
}

private void StartSwClick(object sender, RoutedEventArgs e) { stopwatch.Start(); }

private void StopSwClick(object sender, RoutedEventArgs e) { stopwatch.Stop(); }

private void ResetSwClick(object sender, RoutedEventArgs e)
{
    stopwatch.Stop();
    stopwatch_count = 0;
    value.Text = "00:00:00";
}

This functionality was completely implemented in the GUI source code to avoid using too many asynchronous calls from the application thread; it uses a C# class called DispatcherTimer (that allows the program to generate an event whenever a certain amount of time has passed) and an unsigned integer global variable that acts as a counter: every time the DispatcherTimer throws an event, the associated callback function is called. The callback function is named ClockTick and is responsible for:

  • Updating the counter.
  • Calculating the time passed from the start of the counting process in hours, minutes and seconds.
  • Updating the UI text so that the user can see the current state of the counting process.
In order to let the user interact with the stopwatch, there are three more functions, each associated with a button on the UI:
  • StartSwClick: when the user clicks the Start button, this function makes the DispatcherTimer start.
  • StopSwClick: when the user clicks the Stop button, this function makes the DispatcherTimer stop.
  • ResetSwClick: when the user clicks the Reset button, this function makes the DispatcherTimer stop and resets the counter value to 0.