我的运行时间最多只有 60

My elapsed time is only going up to 60

如何创建超过 60 秒且仅以秒计的经过时间方法。我当前的实现每 60 秒不断重复一次。

代码:

void timer_Tick(object sender, EventArgs e)
{
    time = DateTime.Now.Second.ToString();
    //DateTime.Now.ToLongTimeString();
}


public void timeSetup()
{
    timer = new DispatcherTimer();

    timer.Interval = new TimeSpan(0, 0, 1);
    //timer.Interval = TimeSpan.FromSeconds(1);
    timer.Tick += timer_Tick;

    timer.Start(); 
}

不需要让事情变得比必要的更难:

class TimerClass
{
    public int time;

    void timer_Tick(object sender, EventArgs e)
    {
        time++;
    }


    public void timeSetup()
    {
        timer = new DispatcherTimer();

        timer.Interval = new TimeSpan(0, 0, 1);
        timer.Tick += timer_Tick;

        timer.Start(); 
    }
}

这会每秒调用一次 Tick 处理程序并计算它被调用的次数。这对于长时间测量可能不精确。对于长运行,使用

time = (DateTime.Now - startTime).TotalSeconds;

其中 startTime 被初始化为您启动计时器的时间。