2012-07-11 107 views
0

如何暫停WP7中的定時器? 在我的應用程序中,我想暫停並恢復計時器。但是DispatcherTimer只能啓動和停止。如何暫停計時器?如何暫停DispatchTimer?

回答

0

嘗試將IsEnabled屬性設置爲false以停止它,然後在您希望繼續時返回true。

0

對於暫停/恢復功能,您必須將其構建到您的Tick處理程序中,啓動和停止計時器。

如果你的計時器的時間間隔約爲60秒鐘,然後試試這個:

dispatcher_Timer.Interval = TimeSpan.Fromseconds(30); 

dispatcher_Timer.Tick += new EventHandler(dispatcherTimer_Tickon); 

dispatcher_Timer.Start(); 

private void dispatcherTimer_Tickon(object sender, EventArgs e) 
{ 
    dispatcher_Timer.Tick -= new EventHandler(dispatcherTimer_Tickon); 
    // Do the work for 30 seconds and pause it using stop    
    dispatcher_Timer.Stop(); 

    dispatcher_Timer.Tick += new EventHandler(dispatcherTimer2_Tickon); 
    dispatcher_Timer.Start(); 
} 

private void dispatcherTimer2_Tickon(object sender, EventArgs e) 
{ 
    dispatcher_Timer.Tick -= new EventHandler(dispatcherTimer2_Tickon); 
    // Do the remaining work for 30 seconds and pause it using stop    
    dispatcher_Timer.Stop(); 
} 
0

沒有辦法暫停計時器,後來有它繼續離開的地方。啓用簡單的 調用啓動和停止。

您需要創建自己的計時器才能擁有此功能。

+0

我不認爲這樣做,根據http://stackoverflow.com/questions/3163300/what-is-the-different-between-isenabled-and-start-stop-of-dispatchertimer – 2012-07-11 08:28:44

+1

我不要以爲他在這個職位上是正確的。如果您查看DispatchTimer的源代碼,則isEnabled只會調用Start和Stop。 – Jon 2012-07-11 09:28:53

+0

謝謝你清理! :) – 2012-07-11 09:43:08

1

試試這個: 定義一個全局變量:

private static DateTime EndTime { get; set; } 

然後,當按下啓動按鈕,您進行以下檢查以確定計時器是否已經停止或暫停:

private void btnStartClick(object sender, RoutedEventArgs e) 
{ 
    if (this.dispatcherTimer == null) 
    { 
     this.dispatcherTimer = new DispatcherTimer(); 
     this.dispatcherTimer.Interval = TimeSpan.FromMilliseconds(100); 
     this.dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick); 
    } 

    if (this.EndTime == DateTime.MinValue) 
    { 
     this.EndTime = DateTime.Now + (TimeSpan)this.timeSpan.Value; 
    } 

    this.dispatcherTimer.Start(); 
} 

接下來,當按下暫停按鈕時,您可以停止定時器,因爲下次按下開始按鈕時,您將通過上述檢查:

private void btnPauseClick(object sender, RoutedEventArgs e) 
{ 
    this.dispatcherTimer.Stop(); 
}