我要做的是使用内容管理器在XNA中对声音效果进行Load()
编码,并自动创建一个实例来控制播放。当不再需要声音时,我想知道如何从内存中正确Unload()
它?
此外,我想知道是否甚至需要Unload()
。当我两次调用Load()
时,第二个调用是否正确释放了第一个调用的内存?我猜想C#垃圾收集器会自动处置旧的效果和实例,因为它们已被第二个调用覆盖。它是否正确?
这些是我的自定义MySoundEffect
类中的参数:
// Has sound effect been loaded?
bool loaded;
// Store our SoundEffect resource
SoundEffect effect;
// Instance of our SoundEffect to control playback
SoundEffectInstance instance;
此方法正在加载声音。
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();
}
当不再需要声音时调用此方法:
public void Unload()
{
loaded = false;
instance.Dispose();
effect.Dispose();
}
最佳答案
如果要卸载单个声音,则可以调用Dispose
方法,但是重要的是,您不再需要它,否则您将获得处置元素的优惠。
您可以创建第二个ContentManager
,在其中可以加载仅使用一次的声音,然后对其进行Unload
。
要回答第二个问题,您错了:
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.
关于c# - 正确结束SoundEffectInstance,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19726892/