views:

502

answers:

1

I have a reference to an object. This object has a timer event with a weak reference. Example:

timer.addEventListener(TimerEvent.TIMER, timerHandler, false, 0, true);

Now I remove this reference (test is the variable containing the reference):

test = null;

And yet, the timerHandler keeps being fired. Is this impossible, so that I must have somekind of mistake in my code, without any other possibility?

Or is this indeed not supposed to stop the timer function from being run all the time?

+3  A: 

The garbage collector doesn't operate continually, so it's likely that it just hasn't run yet. When it finally does, your handler should stop being called. If not, there is probably another reference to it.

When I run the example below, I see timer traced indefinitely, even though handler has been set to null and the EventDispatcher has a weak reference. However, if I force the garbage collector to run by uncommenting the System.gc() line (using the debug player), the handler is never called.

package {
  import flash.display.Sprite;
  import flash.events.Event;
  import flash.events.TimerEvent;
  import flash.system.System;
  import flash.utils.Timer;

  public class TimerTest extends Sprite {
    private var timer:Timer;
    public function TimerTest() {
      var handler:Function = createHandler();
      timer = new Timer(1000);
      timer.addEventListener(TimerEvent.TIMER, handler, false, 0, true);
      timer.start();
      handler = null;
      //System.gc();
    }

    private function createHandler():Function {
      return function(e:Event):void {
        trace('timer');
      };
    }
  }
}

In general, you shouldn't rely on the garbage collector for the correct operation of your program.

also
Thanks. Do you recommend the usage of manualy calling the garbage collector using the System.gc() method?
Tom
Hey Tom, no you should not do that (It's actually a debug-player only feature). The garbage collector runs at intervals for preformance reasons (it's an expensive process). If you done with the time events you should clean them up properly by stopping the timer and removing the event listener.
Tyler Egeto