2016-06-28 99 views
1

下面是我试图用作我们正在构建的桌面任务计时器上的已用计时器的代码。现在,当它运行时,它只会计数到60秒,然后重置并且不会添加到分钟中。计时器在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(); 

} 
+0

你能分享定时器初始化方式? –

回答

4

快速修复

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

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

评论

然而,这并没有让很多的意义,因为你可以只直接使用TimeSpan对象:

var timespan = actualTimer.Elapsed; 

此外,我看不到所有的应用程序,但我希望你不需要拨打Application.DoEvents();。由于用户界面应该有机会自动更新......如果不是,那么你需要考虑将任何阻止用户界面的代码移动到不同的线程。


建议

说了这么多,我建议你不要使用计时器在所有曲目经过时间。定时器随着时间的推移会失去准确性最好的方法是在启动过程时存储当前的系统时间,然后当您需要显示“计时器”时,在该点进行按需计算。

一个很简单的例子,以帮助解释一下我的意思是:

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(); 
}