如何在C#中运行同步计时器?我正在编写一个应用程序,它使用计时器在某些事件发生时在屏幕上显示倒计时。我想重用计时器,因为它对应用程序中的某些事情很方便,所以我在计时器周围指定了我想要的词。例如,下面的函数调用:CountdownTimer(90,"Youhave","untilthecomputerreboots");将显示:您有1分30秒,直到计算机重新启动并倒计时。我使用以下内容:privatevoidCountdownTimer(intDuration,stringPrefix,stringSuffix){Countdown=newDispatcherTimer();Countdown.Tick+=newEventHandler(Countdown_Tick);Countdown.Interval=newTimeSpan(0,0,1)CountdownTime=持续时间;CountdownPrefix=前缀;倒计时后缀=后缀;倒计时开始();}privatevoidCountdown_Tick(objectsender,EventArgse){CountdownTime--;如果(CountdownTime>0){intseconds=CountdownTime%60;分钟=倒计时时间/60;Timer.Content=CountdownPrefix;如果(分钟!=0){Timer.Content=Timer.Content+minutes.ToString()+@"minute";如果(分钟!=1){Timer.Content=Timer.Content+@"s";}Timer.Content=Timer.Content+"";}if(seconds!=0){Timer.Content=Timer.Content+seconds.ToString()+@"second";如果(秒!=1){Timer.Content=Timer.Content+@"s";}}Timer.Content=Timer.Content+CountdownSuffix;}else{倒计时停止();例如,等待90秒的时间少于我想要的时间,动作:CountdownTimer(90,"Youhave","untilthecomputerreboots");ExitWindowsEx(2,0)目前它会立即调用重启任何指针都是最受欢迎的!谢谢,Ben就个人而言,我建议在CountdownTimer结束时进行回调-也许将Action作为参数,以便在完成时调用它。私人行动已完成;privatevoidCountdownTimer(intDuration,stringPrefix,stringSuffix,Actioncallback){Countdown=newDispatcherTimer();Countdown.Tick+=newEventHandler(Countdown_Tick);Countdown.Interval=newTimeSpan(0,0,1);倒计时时间=持续时间;CountdownPrefix=前缀;倒计时后缀=后缀;倒计时开始();this.onCompleted=回调;}...else{倒计时停止();动作温度=this.onCompleted;//空委托的线程安全测试if(temp!=null){temp();然后你可以改变你的用法:CountdownTimer(90,"Youhave","untilthecomputerreboots",()=>ExitWindowsEx(2,0));您可以使用AutoResetEvent:System.Threading.AutoResetEvent_countdownFinishedEvent=newAutoResetEvent(false);在CountdownTimer的末尾添加:_countdownFinishedEvent.WaitOne();在Countdown.Stop()之后将其添加到Countdown_Tick的else中:以上是C#学习教程:HowdoyourunasynchronoustimerinC#?如果分享的内容对你有用,需要了解更多C#学习教程,希望大家多多关注—_countdownFinishedEvent.Set();本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如有转载请注明出处:
