I\'m trying to write a simple Resource Manager for the little hobby game I\'m writing. One of the tasks that this resource manager needs to do is unloading unused resources.
It sounds to me that you could just use WeakReference
from the resource manager. The GC will do the rest. You'll need to do a little casting, but it will be simple, and will work.
class Manager {
Dictionary refs =
new Dictionary();
public object this[string key] {
get {
WeakReference wr;
if (refs.TryGetValue(key, out wr)) {
if(wr.IsAlive) return wr.Target;
refs.Remove(key);
}
return null;
}
set {
refs[key] = new WeakReference(value);
}
}
}
static void Main() {
Manager mgr = new Manager();
var obj = new byte[1024];
mgr["abc"] = obj;
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
Console.WriteLine(mgr["abc"] != null); // true (still ref'd by "obj")
obj = null;
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
Console.WriteLine(mgr["abc"] != null); // false (no remaining refs)
}