本地定时器对象事件处理程序 [英] Local Timer Object Event Handler

查看:33
本文介绍了本地定时器对象事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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
}

上面的代码大部分时间都可以工作,但我担心的是如果计时器被垃圾收集会发生什么?是否有可能 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?

我知道计时器有一个内部处理程序列表,但这不会阻止它被垃圾回收.

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

要明确一点:即使您没有对 Timer 的引用,只要当计时器正在运行时,它不会被垃圾收集(想想就好像运行时保持对正在运行的计时器的引用一样).

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

作者:Adobe AIR 团队的 Arno Gourdol

by Arno Gourdol on the Adobe AIR Team

但我一直无法找到权威来源.

but I haven't been able to find an authoritative source.

不过最好不要依赖这种特殊行为,而是将 timer 设为类级变量.

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>

输出:

精灵
计时器
精灵
计时器
收集垃圾
计时器
计时器

sprite
timer
sprite
timer
Collecting garbage
timer
timer

这篇关于本地定时器对象事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆