Search code examples
c#timerdelay

delay timer in C#


I try to connect my RFID to stopwatch, if that's tagging, the timer go start, if that's not, the timer go stop, but there a delay in my timer, can you help me to fix it?

In first tag, timer go normally, after that the timer delay 1 sec.

Here my code program :

int min1, min0, sec1, sec0 = 0;

private void timer1_Tick(object sender, EventArgs e)

    {

        timer1.Interval = 1000;
        label6.Text = min1 + min0.ToString() + ":" + sec1 + sec0.ToString();
        if (sec0 < 9)
        {
            sec0++;
        }
        else
        {
            sec0 = 0;
            sec1++;
        }
        if (sec1 == 6)
        {
            min0++;
            sec1 = 0;
        }

        if (min0 == 10)
        {
            min1++;
            min0 = 0;
        }
        if (min1 == 6)
        {
            min1 = 0;
            min0 = 0;
            sec1 = 0;
            sec0 = 0;
        }           
    }

Solution

  • There seems to be a couple of issues with your code:

    Firstly, you only need to initialize your timer.Interval once. But what you do is initializing your timer Interval repeatedly.

    timer1.Interval = 1000; //declare only once somewhere else, not in the timer tick
    

    Secondly, if you want to start and stop the timer from running according to your RFID connection, then you should have your timer1.Start() and timer1.Stop() methods called following your RFID card "is detected" events (which you must specify somewhere, but this is different topic. For the sake of giving example, I named the event ConnectionChanged)

    private void rfid_ConnectionChanged(object sender RFIDEventArgs e){ //this is a hypothetical event handler
        if(e.IsConnected){
            timer1.Start();
        } else {
            timer1.Stop();
        }
    }
    

    And thirdly, use DateTime struct. Don't use int min1, min0, sec1, sec0 = 0;, DateTime struct will do the calculation job for you. What you need to do is simply re-initializing the DateTime every time the RFID is connected like this:

    DateTime rfidConnectedTime; 
    private void rfid_ConnectionChanged(object sender RFIDEventArgs e){ //this is a hypothetical event handler
        if(e.IsConnected){
            rfidConnectedTime = DateTime.Now;
            timer1.Start();
        } else {
            timer1.Stop();
        }
    }
    

    And then use it like this in your timer1.Tick event:

    private void timer1_Tick(object sender, EventArgs e)
    {
        TimeSpan ts = DateTime.Now - rfidConnectedTime;
        label6.Text = ts.Hours.ToString("d2") + ":" + ts.Minutes.ToString("d2") + ":" + ts.Seconds.ToString("d2");
        //Note: .ToString("d2") is to print each element in two digits like 00 or 01 instead of 0 or 1
    }
    

    Then your code will be neat and simple.