2010-08-16 59 views
1

我正在寫一個應用程序,它使用計時器在屏幕上顯示某個事件發生時的倒計時。我想重複使用計時器,因爲在應用程序中可以使用一些東西,所以我指定了我想包圍計時器的詞語。例如,下面的函數調用:如何在C#中運行同步定時器?

CountdownTimer(90, "You have ", " until the computer reboots"); 

會顯示:

You have 1 minute 30 seconds until the computer reboots 

,然後倒計時。

我使用下面的代碼:

private void CountdownTimer(int Duration, string Prefix, string Suffix) 
    { 
     Countdown = new DispatcherTimer(); 
     Countdown.Tick += new EventHandler(Countdown_Tick); 
     Countdown.Interval = new TimeSpan(0, 0, 1); 

     CountdownTime = Duration; 
     CountdownPrefix = Prefix; 
     CountdownSuffix = Suffix; 
     Countdown.Start(); 
    } 

    private void Countdown_Tick(object sender, EventArgs e) 
    { 
     CountdownTime--; 
     if (CountdownTime > 0) 
     { 
      int seconds = CountdownTime % 60; 
      int minutes = CountdownTime/60; 

      Timer.Content = CountdownPrefix; 

      if (minutes != 0) 
      { 
       Timer.Content = Timer.Content + minutes.ToString() + @" minute"; 
       if (minutes != 1) { Timer.Content = Timer.Content + @"s"; } 
       Timer.Content = Timer.Content + " "; 
      } 

      if (seconds != 0) 
      { 
       Timer.Content = Timer.Content + seconds.ToString() + @" second"; 
       if (seconds != 1) { Timer.Content = Timer.Content + @"s"; } 
      } 

      Timer.Content = Timer.Content + CountdownSuffix; 

     } 
     else 
     { 
      Countdown.Stop(); 
     } 

    } 

如何使這個同步運行?例如,我希望以下內容等待90秒,然後重新啓動:

CountdownTimer(90, "You have ", " until the computer reboots"); 
ExitWindowsEx(2,0) 

而目前它立即調用重啓。

任何指針都將是最受歡迎的!

感謝,

回答

4

個人而言,我建議有一個回調發生在你的CountdownTimer結束 - 也許服用Action作爲參數,例如,當它完成它會被稱爲。

private Action onCompleted; 
private void CountdownTimer(int Duration, string Prefix, string Suffix, Action callback) 
{ 
    Countdown = new DispatcherTimer(); 
    Countdown.Tick += new EventHandler(Countdown_Tick); 
    Countdown.Interval = new TimeSpan(0, 0, 1); 

    CountdownTime = Duration; 
    CountdownPrefix = Prefix; 
    CountdownSuffix = Suffix; 
    Countdown.Start(); 

    this.onCompleted = callback; 
} 
... 
    else 
    { 
     Countdown.Stop(); 
     Action temp = this.onCompleted; // thread-safe test for null delegates 
     if (temp != null) 
     { 
      temp(); 
     } 
    } 

然後你可以只改變你的使用情況:

CountdownTimer(90, "You have ", " until the computer reboots", 
    () => ExitWindowsEx(2,0)); 
+0

我喜歡這個回答+1 – 2010-08-16 16:11:24

2

你可以使用的AutoResetEvent:

_countdownFinishedEvent.WaitOne(); 

System.Threading.AutoResetEvent _countdownFinishedEvent 
    = new AutoResetEvent(false); 

CountdownTimer末尾添加這

並加上s內Countdown_Tick只是Countdown.Stop()

_countdownFinishedEvent.Set();