1

What I want to do is to Load() a sound effect in XNA using the Content Manager and automatically create a instance to control playback. When the sound is no longer needed, I was wondering how to properly Unload() it from memory?

Furthermore, I was wondering if Unload() is even needed. When I call Load() twice, does the second call properly free the memory of the first call? I would guess that the C# garbage collector automatically disposes the old effect and instance as they are being overwritten by the second call. Is this correct?

These are the parameters in my custom MySoundEffect class:

// Has sound effect been loaded?
bool loaded;

// Store our SoundEffect resource
SoundEffect effect;

// Instance of our SoundEffect to control playback
SoundEffectInstance instance;

This method is loading the sound.

public void Load(String location)
{
    effect = Content.Load<SoundEffect>(location);

    if (effect != null) loaded = true;
    else
    {
        Error.Happened("Loading of sound effect " + location + " failed.");
        return;
    }

    // Create instance
    instance = effect.CreateInstance();
}

This is called when the sound is no longer needed:

public void Unload()
{
    loaded = false;

    instance.Dispose();

    effect.Dispose();
}
ares_games
  • 1,019
  • 2
  • 15
  • 32

1 Answers1

1

If you want to unload a single sound you can call Dispose method, but it's important that you never need it again, or you'll receive an excepion of disposed element.
You can create a second ContentManager where you can load the sounds that you use only one time, and then Unload it.

To answer to your second question, you are wrong:

Each instance of ContentManager will only load any given resource once. The second time you ask for a resource, it will return the same instance that it returned last time.

To do this, ContentManager maintains a list of all the content it has loaded internally. This list prevents the garbage collector from cleaning up those resources - even if you are not using them.

pinckerman
  • 4,115
  • 6
  • 33
  • 42
  • 1
    So when I overwrite all references to a asset loaded using the ContentManager, it is still not disposed by the Garbage Collector? Wouldn't this undermine the sense of a GC completely? – ares_games Nov 11 '13 at 16:11
  • I think you need to manually unload them calling Content.Unload(). – pinckerman Nov 11 '13 at 16:33
  • Does [this](http://stackoverflow.com/questions/19911006/garbage-collector-behaviour/19911036?noredirect=1#19911036) contradicts that? – ares_games Nov 11 '13 at 16:49
  • I referenced [this](http://stackoverflow.com/a/9870420/2498113) answer. I trust a user that has 19k rep points. – pinckerman Nov 11 '13 at 16:57
  • If you look at that question again you'll see that the answer is changed, as I told you. – pinckerman Nov 11 '13 at 20:21