Confused about garbage collection and events with weak references in actionscript 3

1.2k views Asked by At

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?

1

There are 1 answers

2
also On BEST ANSWER

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.