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. I can think of doing this in two ways:
When an object no longer requires a reference to the resource, it must call a method of the Resource Manager to signify it is no longer using it; or
When an object no longer requires a reference to the resource, it simply sets it to null. Then when the Resource Manager is asked to unload unused resources, it gets the reference count (via reflection?) of each resource. If the reference count is one (the Resource Manager will have a reference to the resource), unload the resource.
Is there any way to acheive the second solution in C#? Thanks.
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<string, WeakReference> refs =
new Dictionary<string, WeakReference>();
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)
}