简体   繁体   中英

how to check for the elapsed time of a timer in c#

My code is below:

    private void Timer_Tick(object sender, EventArgs e)
    {
        time--;
        Timelbl.Text = "Time: " + time + " seconds";

        if (time == 0)
        {
            Timer.Stop();
            Timelbl.Text = "Time: " + 0 + " seconds";
        }
    }

I want to know how I can check how long it has been since the timer has started. For example if the variable time was 30,after 20 seconds, I want to know that the timer started 20 seconds ago, but the problem is that the value of the variable time changes all the time so how will I go about doing this in c#?

So this basically boils down to Timer vs. Stopwatch .

A Timer per the docs: Generates an event after a set interval, with an option to generate recurring events.

A Stopwatch per the docs: Provides a set of methods and properties that you can use to accurately measure elapsed time.

You can set up a Stopwatch to be a property of your Form and then update the UI in your Timer event to update the UI and show the elapsed time by doing something like:

Timelbl.Text = "Time: " + (sw.ElapsedMilliseconds / 1000).ToString() + " seconds";

Assuming sw is of type Stopwatch .

Let me know if you need specific help setting up a Stopwatch on your form / if you hit snags getting that set up.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM