Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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..

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
181 views
Welcome To Ask or Share your Answers For Others

1 Answer

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();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...