Skip to main content
 首页 » 编程设计

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

2024年02月05日11thcjp

下面是我试图在我们正在构建的桌面任务计时器上用作经过计时器的代码。现在,当它运行时,它只计数到 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(); 
}