gpt4 book ai didi

c# - 如何在 C# 中运行同步计时器?

转载 作者:太空宇宙 更新时间:2023-11-03 18:47:00 25 4
gpt4 key购买 nike

我正在编写一个应用程序,它使用计时器在屏幕上显示某个事件发生时的倒计时。我想重复使用计时器,因为它对应用程序中的一些事情很方便,所以我指定了我想要环绕计时器的词。例如,下面的函数调用:

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)

而目前它会立即调用重启。

欢迎任何指点!

谢谢,

最佳答案

就我个人而言,我建议在您的 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));

关于c# - 如何在 C# 中运行同步计时器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3494861/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com