[英]From AS3 to C# a simple elapsed Timer
I need to set up a simple elapsed Timer in C# (MonoBehavior) that calls a method when complete, but can also be cancelled before finishing. 我需要在C#(MonoBehavior)中设置一个简单的经过计时器,该计时器在完成时调用方法,但也可以在完成之前将其取消。 If cancelled or stopped, it automatically resets its interval. 如果取消或停止,它将自动重置其间隔。 I don't need anything fancy like threading. 我不需要像线程这样的东西。
Reading over the documentation on C# Timers 阅读有关C#计时器的文档
https://msdn.microsoft.com/en-us/library/System.Timers.Timer%28v=vs.110%29.aspx https://msdn.microsoft.com/zh-cn/library/System.Timers.Timer%28v=vs.110%29.aspx
still a bit confused. 还是有点困惑。 For instance, when you set mytimer.Enabled=false does it also reset the timer back to 0? 例如,当您设置mytimer.Enabled = false时 ,是否还会将计时器重置为0?
Perhaps I should be looking at Coroutines instead?(this is for Unity) 也许我应该看看协程呢?(这是针对Unity的)
In AS3 I would do something like this 在AS3中,我会做这样的事情
private var _delayTimer:Timer;
//create a Timer object that runs once for 1 second
_delayTimer = new Timer(1000,1);
//add handler
_delayTimer.addEventListener(TimerEvent.COMPLETE, onDelay);
//start timer
_delayTimer.start();
private function onDelay(e:TimerEvent):void{
trace('delay finished!);
}
//some other method to interrupt-stop and reset the delay timer
private function foo():void{
_delayTimer.reset();
}
By using System.Timers.Timer
, you are using multi-threading - it's quite likely this is not what you want. 通过使用System.Timers.Timer
,您正在使用多线程-这很可能不是您想要的。
Instead, you probably want System.Windows.Forms.Timer
- this will post the timer event back on the UI thread (if you're using Windows Forms, of course). 相反,您可能需要System.Windows.Forms.Timer
这会将计时器事件发回到UI线程上(当然,如果您使用的是Windows Forms)。
You can use Start
and Stop
the way you want, because there's actually no ticking clock - it just registers a callback from Windows in the future, basically. 您可以按自己想要的方式使用“ Start
和“ Stop
”,因为实际上没有滴答时钟-基本上,它将来只会在Windows中注册回调。
Relevant piece of documentation from MSDN: 来自MSDN的相关文档:
Calling Start after you have disabled a Timer by calling Stop will cause the Timer to restart the interrupted interval. 在通过调用停止禁用了计时器之后调用启动将导致计时器重新开始中断的间隔。 If your Timer is set for a 5000-millisecond interval, and you call Stop at around 3000 milliseconds, calling Start will cause the Timer to wait 5000 milliseconds before raising the Tick event. 如果将计时器设置为5000毫秒的间隔,并且您在3000毫秒左右调用Stop,则调用Start将导致计时器等待5000毫秒,然后再引发Tick事件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.