计时器在 60 秒后重置

1 c# timer

下面是我试图在我们正在构建的桌面任务计时器上用作经过计时器的代码。现在,当它运行时,它只计数到 60 秒,然后重置并且永远不会增加到分钟。

//tick timer that checks to see how long the agent has been sitting in the misc timer status, reminds them after 5 mintues to ensure correct status is used
private void statusTime_Tick(object sender, EventArgs e)
{
    counter++;
    //The timespan will handle the push from the elapsed time in seconds to the label so we can update the user
    //This shouldn't require a background worker since it's a fairly small app and nothing is resource heavy

    var timespan = TimeSpan.FromSeconds(actualTimer.Elapsed.Seconds);

    //convert the time in seconds to the format requested by the user
    displaycounter.Text=("Elapsed Time in " + statusName+" "+ timespan.ToString(@"mm\:ss"));

    //pull the thread into updating the UI
    Application.DoEvents();

}
Run Code Online (Sandbox Code Playgroud)

mus*_*fan 5

快速解决

我相信问题在于您使用的Seconds是 0-59。您想TotalSeconds与现有代码一起使用:

var timespan = TimeSpan.FromSeconds(actualTimer.Elapsed.TotalSeconds);
Run Code Online (Sandbox Code Playgroud)

注释

但是,这没有多大意义,因为您可以直接使用该TimeSpan对象:

var timespan = actualTimer.Elapsed;
Run Code Online (Sandbox Code Playgroud)

另外,我看不到您的所有应用程序,但我希望您不需要调用Application.DoEvents();. 由于 UI 应该在有机会时自动更新......如果它没有,那么你想看看将阻止 UI 的任何代码移动到不同的线程。


推荐

尽管如此,我建议您根本不要使用计时器来跟踪经过的时间。随着时间的推移,计时器可能会失去准确性。最好的方法是在您启动进程时存储当前系统时间,然后当您需要显示“计时器”时在该点进行按需计算。

一个非常简单的例子来帮助解释我的意思:

DateTime start;

void StartTimer()
{
    start = DateTime.Now;
}

void UpdateDisplay()
{
    var timespan = DateTime.Now.Subtract(start);
    displaycounter.Text = "Elapsed Time in " + statusName + " " + timespan.ToString(@"mm\:ss"));
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用计时器UpdateDisplay定期调用您的方法:

void statusTime_Tick(object sender, EventArgs e)
{
    UpdateDisplay();
}
Run Code Online (Sandbox Code Playgroud)