简体   繁体   中英

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. If cancelled or stopped, it automatically resets its interval. I don't need anything fancy like threading.
Reading over the documentation on C# Timers
https://msdn.microsoft.com/en-us/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?
Perhaps I should be looking at Coroutines instead?(this is for Unity)

In AS3 I would do something like this

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.

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).

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.

Relevant piece of documentation from 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM