flash - 本地定时器对象事件处理程序

标签 flash apache-flex actionscript-3

我在类函数中有以下代码:

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
}

上面的代码大部分时间都可以工作,但我担心的是如果计时器被垃圾收集会发生什么?是否有可能 onTimerComplete 永远不会触发,因为没有其他对计时器的引用?

我知道 timer 有一个内部处理程序列表,但这不会阻止它被 GC 处理。

最佳答案

网上有一些关于运行计时器从不被垃圾收集的引用资料,e.g. :

Just to be clear: even if you have no references to a Timer, as long as the timer is running, it will not be Garbage Collected (think of it as if the runtime was keeping a reference to running timers).

by Arno Gourdol on the Adobe AIR Team


但我一直无法找到权威来源。
可能最好不要依赖这种特殊行为,而是让 timer一个类级别的变量,虽然。
建议事件监听器阻止计时器被垃圾收集的答案是不正确的。引用是从计时器到监听器函数 ( onTimerComplete ),因此如果计时器可访问,则监听器函数不会被垃圾收集,反之亦然。这很容易测试:
<?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>
输出:

sprite
timer
sprite
timer
Collecting garbage
timer
timer

关于flash - 本地定时器对象事件处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5891354/

相关文章:

html - Flash 对象在 chrome 中的位置固定元素

apache-flex - 有没有工具可以将对象状态捕获到磁盘?

ios - Action script 3.0 问题,我的 swf 无法卸载

html - Flash 播放器覆盖绝对定位元素

actionscript-3 - 带有Flash的youtube搜索控件的位置栏

java - 是否有可用于 Java、C++ 和 JS 的可下载的 eclipse 包

actionscript-3 - Flash AS3 多点触摸事件处理程序

actionscript-3 - Flash 事件执行顺序

flash - 如何在浏览器上播放avi文件

actionscript-3 - 如何将列添加到 Adob​​e flex mx :DataGrid in mxml and/or actionsctpt?