C# - Get number of references to object

前端 未结 5 2002
醉梦人生
醉梦人生 2020-12-05 05:37

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.

5条回答
  •  春和景丽
    2020-12-05 06:34

    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)
    }
    

提交回复
热议问题