Csharp/C#教程:你如何在C#中运行同步计时器?分享


你如何在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) 

而目前它立即调用重启。

任何指针都是最受欢迎的!

谢谢,

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

您可以使用AutoResetEvent:

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

CountdownTimer结束时添加:

 _countdownFinishedEvent.WaitOne(); 

Countdown.Stop()之后将其添加到Countdown_Tick的else中:

上述就是C#学习教程:你如何在C#中运行同步计时器?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 _countdownFinishedEvent.Set(); 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1037608.html

(0)
上一篇 2022年1月25日
下一篇 2022年1月25日

精彩推荐