问题描述
我有以下的code类中的函数:
I have the following code in a class function :
public function foo():void
{
var timer:Timer = new Timer(10000,1);
timer.addEventListener(TimerEvent.TIMER_COMPLETE,onTimerComplete);
timer.start();
}
public function onTimerComplete(e:TimerEvent):void
{
// do stuff
}
以上code工作的大部分时间,但我担心的是,如果计时器被垃圾收集,会发生什么?难道onTimerComplete将永远不会触发,因为没有其它引用计时器?
The above code works most of the time but my concern is what happens if timer gets garbage collected? Is it possible that onTimerComplete will never fire because there are no other references to timer?
我知道计时器都有处理程序的内部列表中,但不会被GC'ed。
I know timer has an internal list of handlers but that won't keep it from being GC'ed.
推荐答案
有在网络上的一些参考运行计时器绝不被垃圾收集,的:
There are some references on the web to running timers never being garbage collected, e.g.:
只是要清楚:即使你有一个计时器没有提及,只要 作为定时器运行,它不会被垃圾回收(想想 它仿佛运行时是保持一个引用运行计时器)。
由阿诺Gourdol在Adobe AIR团队
by Arno Gourdol on the Adobe AIR Team
但我一直没能找到一个权威的来源。
but I haven't been able to find an authoritative source.
也许最好不要依赖这个特殊的行为,而让定时器
A类级别的变量,虽然。
Probably best to not rely on this special behavior and instead make timer
a class-level variable, though.
回答提示事件侦听器保持计时器被垃圾收集是不正确的。参考从定时器监听功能( onTimerComplete
),所以如果定时器可达那么监听功能将不会被垃圾回收,而不是相反。这很容易测试:
Answers suggesting that event listeners are keeping the timer from being garbage collected are incorrect. The reference is from the timer to the listener function (onTimerComplete
), so if the timer is reachable then the listener function won't be garbage collected, but not vice versa. This is easily tested:
<?xml version="1.0" encoding="utf-8"?>
<s:Application
xmlns:s="library://ns.adobe.com/flex/spark"
creationComplete="application1_creationCompleteHandler(event)">
<fx:Script>
<![CDATA[
private var _gcTimer:Timer;
protected function application1_creationCompleteHandler(event:FlexEvent):void {
var timer:Timer = new Timer(30, 4);
timer.addEventListener(TimerEvent.TIMER, onTimer, false, 0, true);
var sprite:Sprite = new Sprite();
sprite.addEventListener(Event.ENTER_FRAME, onSprite, false, 0, true);
_gcTimer = new Timer(59, 1);
_gcTimer.addEventListener(TimerEvent.TIMER, garbageCollect);
timer.start();
_gcTimer.start();
}
private function onTimer(event:TimerEvent):void {
trace("timer");
}
private function onSprite(event:Event):void {
trace("sprite");
}
]]>
</fx:Script>
</s:Application>
输出:
精灵
计时器
精灵
计时器
收集垃圾
计时器
计时器
这篇关于本地计时器对象事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!