2016-06-28 105 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(); 
}