Stop watch delay using timer c#

混江龙づ霸主 提交于 2019-12-14 03:25:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!