简体   繁体   English

如何在C#中检查计时器的经过时间

[英]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#? 例如,如果可变时间是30秒后20秒,我想知道计时器是在20秒前启动的,但是问题是可变时间的值一直都在变化,所以我将如何在c#中执行此操作?

So this basically boils down to Timer vs. Stopwatch . 因此,这基本上可以归结为Timer vs. Stopwatch

A Timer per the docs: Generates an event after a set interval, with an option to generate recurring events. 每个文档都有一个Timer :在设置的时间间隔后生成事件,并带有生成重复事件的选项。

A Stopwatch per the docs: Provides a set of methods and properties that you can use to accurately measure elapsed time. 每个文档的Stopwatch :提供一组方法和属性,可用于准确测量经过的时间。

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: 您可以将Stopwatch设置为Form的属性,然后通过执行以下操作来更新Timer事件中的UI,以更新UI并显示经过的时间:

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

Assuming sw is of type Stopwatch . 假设swStopwatch类型。

Let me know if you need specific help setting up a Stopwatch on your form / if you hit snags getting that set up. 让我知道您是否需要在表单上设置Stopwatch特定帮助/如果遇到障碍,请进行设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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