In my WinUI 3.0 app I have a stopwatch that counts up every second. Often, but not always, it stutters while counting up. For example, the timer will stay at 0:00:04 for longer than a second, then jump to 0:00:06.
Is there something I am doing wrong?
My code:
public static DateTime startTime;
private readonly System.Timers.Timer timer = new(1000);
public MainPage()
{
ViewModel = App.GetService<MainViewModel>();
this.InitializeComponent();
timer.AutoReset = true;
timer.Elapsed += Timer_Tick;
}
private void StartButton_Click(object sender, RoutedEventArgs e)
{
if (!timer.Enabled)
{
startTime = DateTime.Now;
timer.Start();
}
else
{
DateTime stopTime = DateTime.Now;
timer.Stop();
timerLabel.Text = "0:00:00";
}
}
private void Timer_Tick(object sender, EventArgs e)
{
DispatcherQueue.TryEnqueue(() =>
{
timerLabel.Text = DateTime.Now.Subtract(startTime).ToString(@"h\:mm\:ss");
});
}