Unloading an external swf loaded into a new application domain

Hi everyone, I’ve got a question about application domains. I am working on a virtual world that contains several mini-games. At the moment, I can launch mini games as external swf’s and pass information back and forth between the the mini-game and virtual world. When I am finished, I remove the external swf from the stage.

I recently talked with another developer about application domains and how they keep external swf’s modular and separate from the system application domain such that any class definitions that are loaded from the external swf are contained within its own domain and do not leak over into the system domain. In a sense, these class definitions can act as a “parasite,” consuming memory. Therefore, I went back and reworked some of the code so that my loaded external swf is loaded into its own application domain:


var rand:Number = Math.floor(Math.random() * 1000);
var request:URLRequest = new URLRequest(filename + "?x=" + rand.toString());
var myGame:Loader = new Loader();
			
var context:LoaderContext = new LoaderContext(false, new ApplicationDomain());
request.url = filename + "?x=" + rand.toString();
myGame.contentLoaderInfo.addEventListener(Event.COMPLETE, loadGameIntoWorld);
						
// Load the game
myGame.load(request, context);	

This block of code appears to load the game into its own domain, which is what I want it to do. However, when the game is finished, I want to completely unload the loaded swf. I’ve found two ways to do this:

  1. Remove the content of the loaded swf from the stage and make sure that all of its event listeners, timers, etc have been stopped.
  2. Call the “unload” method from the loader object that loaded the external swf

So, when my mini-game is finished, it stops all event listeners, timers, audio, etc and sends a shared event from the mini-game back to the world. When I catch this event, I try to do the following:


var game:MovieClip = _gameComp.removeChildAt(0) as MovieClip;
game.loaderInfo.loader.unload();

This throws the following error:
ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller.
at flash.display::Loader/unload()

I really need to unload the external swf because as soon as it is unloaded, all of the objects that were loaded in that domain should then unload and no longer take up space in the system domain once garbage collection runs through. I’ve run the program in the Flex Profiler and even if I take the “unload” statement out and just remove it from the stage, the program holds on to all instances of class definitions created within this application domain. Please help, am I going about this in the wrong way? Thanks!

Regards,

Will