Search code examples
c#timersystem

System timer c#


I have some code involving a system timer that starts counting in seconds when a file is added to a folder then stops when it is removed. when the timer is stopped is shows the correct time however when I restart the timer it picks up where it left off instead of restarting at 0. Here is my code..

        t2 = new System.Timers.Timer();
        t2.AutoReset = true;
        t2.Interval = 1000;
        t2.Elapsed += OnTimeEvent2;
        watch();

    }
    private void OnTimeEvent2(object sender, System.Timers.ElapsedEventArgs e)
    {
        Invoke(new Action(() =>
        {

            s += 1;

            lblSeconds.Text = string.Format(s.ToString());

        }));
    }

Solution

  • Use the System.Windows.Forms.Timer so you don't need to worry about cross-threading. Here's a quick example of using the Stopwatch class:

    private System.Windows.Forms.Timer tmr = new Timer();
    private System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
    
    private void Form1_Load(object sender, EventArgs e)
    {
        tmr.Interval = 1000;
        tmr.Tick += Tmr_Tick;
        tmr.Start();
        sw.Start();
    }
    
    private void Tmr_Tick(object sender, EventArgs e)
    {
        lblSeconds.Text = ((int)sw.Elapsed.TotalSeconds).ToString();
    }
    

    To make the timer start from zero again, simply use the Restart() method:

    private void button1_Click(object sender, EventArgs e)
    {
        sw.Restart();
    }