Reference Counting in Managed Code

Today, while coding Galactic Wars v2.0, I stumbled upon a problem I have been having with content since I started working with XNA. The following diagram shows how easy it is to create the problem and how devastating it can be to any application. In my case, I have two (or more) menus that are referencing a piece of content.

Multiple References

Each menu references the same managed object which is really a wrapper for a second managed object (Texture2D in this case). The second object is a managed wrapper for the underlying unmanaged data, again in this case it is texture data. The problem is when one menu is being phased out (unloaded) and another is being phased in (loaded). The menu being loaded grabs a reference to the content before the other menu can unload it. The ordering is done this way to ensure that a menu actually loads its content before the current menu is unloaded.

After the menu is done loading content, the second menu is unloaded which drops the content and releases the unmanaged memory. Aha! The problem stems from the last point: I am trying to manage unmanaged memory when I should just let the GC take care of it. The reason I do this is for performance reasons, primarily on the Zune. Instead of letting textures just sit around, I release them when they are no longer needed to avoid piling up the garbage.

So what is the solution?

  1. Dereference the Managed Object

    I would love to do this but unfortunately it introduces a second problem. If every menu (object using the content) dereferences the asset, it still will not be collected by the GC. The AssetManager still holds a reference which is now being unused and thus memory is wasted. The upside to this is that I do not need to implement the second option…

  2. Reference Counting!

    By implementing a counter on the asset itself and asking developers to always call Unload or Unload(ILoadable) on the AssetManager, I can guarantee that no Asset will be disposed while another object is using it. The downside is that it is an ugly implementation of something that is done in the GC anyways. The major upside is that even if developers use the previous method, the GC will still eventually catch the wasted memory.

So now Thrust’s AssetManager and IAsset require (and implement) reference counting to avoid the problem described above. And it works wonderfully.

No Comments

No comments yet.

RSS feed for comments on this post.

Leave a comment

You must be logged in to post a comment.

WordPress Themes