我正在寫一個應用程序,它使用計時器在屏幕上顯示某個事件發生時的倒計時。我想重複使用計時器,因爲在應用程序中可以使用一些東西,所以我指定了我想包圍計時器的詞語。例如,下面的函數調用:如何在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)
而目前它立即調用重啓。
任何指針都將是最受歡迎的!
感謝,
本
我喜歡這個回答+1 – 2010-08-16 16:11:24