Actionscript 3: Do self event listeners prevent an

2019-03-03 02:29发布

问题:

I know that event listeners and references to an object will prevent the garbage collector from dealing with objects. My question is, will an event listener placed on an object, listening to the same object, prevent that object from being garbage collected?

I ask because it seems like this is happening to me. I am breaking all my references to an object but I am still seeing traces when its timer goes off. At the same time, it seems like this should not prevent the collection because it would create allocated but unreferenceable memory.

回答1:

No, but.

The AVM2 garbage collector is supposed to find unreachable objects. But because garbage collection is non-deterministic, it's very hard to rely on or even test this behaviour -- it could be that the garbage collector is working perfectly, but not bothering to run the mark-and-sweep since you have enough RAM free.

It's a good idea to remove event listeners when you're done with the object, even if they're from the object itself (i.e. circular references). Why is this a good idea? Because you never know when the garbage collector is going to run. If you want deterministic behaviour, always remove listeners in a deterministic fashion, especially for time-sensitive events like TIMER and ENTER_FRAME, otherwise you're creating a race condition between your listeners running and the garbage collector running. The garbage collector only runs periodically.

In general, if you want to attach event listeners without creating an additional reference to the object, pass true to the useWeakReference parameter of addEventListener(). If you want to stop receiving the events right away, though, you'll still need to manually detach your event listeners as soon as you're done with the object.



回答2:

Yes, this will stop the GC from cleaning up your object. A hacky way to try to prevent this is to use weak references when adding listeners.

 myobj.addEventListener(Event.EVENT, eventHandler, false, 0, true);

The last true flag will set the listener to use a weak object reference.

Best practice would be to keep track and always remove any active listeners before nulling your object.

Check out this great blog post for more info on this topic

http://gskinner.com/blog/archives/2006/06/as3_resource_ma.html