问题
I want to add a stopWatch to my form but the one i made is lagging behind the time of other timer in pc. Can you give any solution for that? (My timer interval is 100). this is my code:
int min, sec, ms = 0;
private void timer1_Tick(object sender, EventArgs e)
{
Time.Text = min + ":" + sec + ":" + ms.ToString();
ms++;
if (ms > 9)
{
ms = 0;
sec++;
}
if (sec > 59)
{
sec = 0;
min++;
}
}
private void timer_Click(object sender, EventArgs e)
{
timer1.Start();
}
It working but with easy delay. I have tried to change so many things but none of them is working..
回答1:
Timer's tick is not as precise as you think. So It would be better if you calculate the difference between start time and the time tick invoked.
DateTime startTime = DateTime.Now;
private void timer1_Tick(object sender, EventArgs e)
{
Time.Text = DateTime.Now.Subtract(startTime).ToString(@"mm\:ss\.ff");
}
private void timer_Click(object sender, EventArgs e)
{
startTime = DateTime.Now;
timer1.Start();
}
回答2:
Your timer interval is 100ms, so create a TimeSpan object, as a class variable, for that
TimeSpan _100ms = new TimeSpan(0,0,0,0,100);
Add this to your TimeSpan object that you're using to track time
TimeSpan ts = new TimeSpan();
ts = ts.Add(_100ms);
To display it to your UI:
private void timer1_Tick(object sender, EventArgs e)
{
ts = ts.Add(_100ms);
Time.Text = ts.ToString(@"hh\:mm\:ss\.fff");
}
Fiddle Demo
来源:https://stackoverflow.com/questions/31777476/stop-watch-delay-using-timer-c-sharp