c# - 计时器在 60 秒后重置

标签 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();

}

最佳答案

快速修复

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

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

评论

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

var timespan = actualTimer.Elapsed;

此外,我看不到您的所有应用程序,但我希望您不需要调用 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"));
}

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

void statusTime_Tick(object sender, EventArgs e)
{
    UpdateDisplay();
}

关于c# - 计时器在 60 秒后重置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38077999/

相关文章:

c# - Visual Studio/IIS Express 间歇性错误

Php 计算秒数到最近的刻钟

java - Java中计算耗时

java - 每天、每周、每月、每年调用一个方法

vba - Excel VBA 计时器性能因哪个工作表处于事件状态而异?

c# - .Net继承和方法重载

c# - WPF 如何将 Image.Source 居中

c# - 用户可以看到 Silverlight 代码吗?

c# - 如何将 float 组转换为 byte[] 并返回?

multithreading - 定时器和javafx