Timer Control ticking slower than real life in C#

I am making a simple Timer application in windows forms using C#. The problem is when I start the timer, it ticks slightly slower than a real timer. Anyone knows why and how I can solve this?
3 Replies
Alex
Alex8mo ago
Here is my code if anyone wants to see it
using System;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Timers;
using System.Windows.Forms;
using System;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Timers;
using System.Windows.Forms;
in the contructor of my form:
Timer1.Interval = 1000;
Timer1.Elapsed += Timer1_Tick;
Timer1.Interval = 1000;
Timer1.Elapsed += Timer1_Tick;
Then there is the event:
private void Timer1_Tick(object sender, ElapsedEventArgs e)
{
try
{
Invoke(new Action(() =>
{
Seconds1++;
if (Seconds1 == 60)
{
Seconds1 = 0;
Minutes1++;
}
if (Minutes1 == 60)
{
Minutes1 = 0;
Hours1++;
}
if (Hours1 > 0) grpMainTimer.Text = $"{Hours1}h {Minutes1}m {Seconds1}s";
else if (Minutes1 > 0) grpMainTimer.Text = $"{Minutes1}m {Seconds1}s";
else grpMainTimer.Text = $"{Seconds1}s";
}));
}
catch { Application.Exit(); }
}
private void Timer1_Tick(object sender, ElapsedEventArgs e)
{
try
{
Invoke(new Action(() =>
{
Seconds1++;
if (Seconds1 == 60)
{
Seconds1 = 0;
Minutes1++;
}
if (Minutes1 == 60)
{
Minutes1 = 0;
Hours1++;
}
if (Hours1 > 0) grpMainTimer.Text = $"{Hours1}h {Minutes1}m {Seconds1}s";
else if (Minutes1 > 0) grpMainTimer.Text = $"{Minutes1}m {Seconds1}s";
else grpMainTimer.Text = $"{Seconds1}s";
}));
}
catch { Application.Exit(); }
}
sigma
sigma8mo ago
When you say that it ticks slower than real life, you measured it with another timer? So, when you used another timer, and that timer counted 1 sec, your timer was still counting? One thing I would recommend is to not use string interpolation, as you may be allocating a new string every time, although I may be wrong, since I don't remember the specifics in .net Also, in Windows Forms, is there a way to separate your UI code and your Timer code in different threads?
Alex
Alex8mo ago
yes i make them both run at the sane starting point, and after over 10m I saw a difference yes i am pretty sure, but i dont know how as I am not familoar with threads
Want results from more Discord servers?
Add your server
More Posts