你怎么跑在C#中的同步计时器? [英] How do you run a synchronous timer in C#?
问题描述
我写它使用一个计时器在屏幕上显示一个倒计时,当一些事件发生的应用程序。我想重新使用计时器,因为这将是很方便的在应用程序的几件事情,所以我指定我想包圆计时器的话。例如,下面的函数调用:
I am writing an app which uses a timer to display a countdown on screen to when some event happens. I want to reuse the timer, as it would be handy for a few things in the app, so I specify the words I want to wrap round the timer. For example, the following function call:
CountdownTimer(90, "You have ", " until the computer reboots");
会显示:
You have 1 minute 30 seconds until the computer reboots
,然后倒计时。
我用下面的code:
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秒,然后重新启动:
How do I make this run synchronously? For example I would want the following to wait 90 seconds and then reboot:
CountdownTimer(90, "You have ", " until the computer reboots");
ExitWindowsEx(2,0)
,而当present立即调用重新启动。
Whereas it calls the reboot immediately at present.
任何指针将是最欢迎!
谢谢,
本
推荐答案
个人而言,我建议有一个回调发生在你CountdownTimer年底 - 也许服用动作
作为参数,例如,当它完成它会被调用。
Personally, I'd recommend having a callback happen at the end of your CountdownTimer - perhaps taking an Action
as an argument, such that when it completed it'd be called.
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();
}
}
然后,你可以只改变您的使用情况为:
Then you could just change your usage to:
CountdownTimer(90, "You have ", " until the computer reboots",
() => ExitWindowsEx(2,0));
这篇关于你怎么跑在C#中的同步计时器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!