简体   繁体   中英

Dictionary of weak and non-weak references

I have a custom type MyClass and a factory class Factory that creates objects of type MyClass upon request.

The Factory stores created objects in a dictionary because objects are expensive to create and there are times when same object can be asked to be created multiple times. Each object with the same tag must be created one time only.

class MyObject
{
    // .. not important
}

class Factory
{
    private Dictionary<int, MyObject> m_objects = new Dictionary<int, MyObject>();

    public MyObject CreateObject(int tag, params object[] parameters)
    {
        MyObject obj;
        if (!m_objects.TryGetValue(tag, out obj))
        {
            obj = new MyObject();
            // .. some initialization
            m_objects.Add(tag, obj);
        }

        return obj;
    }
}

Objects might be and might be not stored somewhere outside Factory for unknown amount of time. Objects might be changed after creation. There are times when Factory stores reference to an object and the object is not stored anywhere else.

Now I want let garbage collector to do its job. I want objects not stored anywhere outside Factory and not changed to be collected.

My first thought was to use weak references for values in dictionary inside Factory but it seems like this approach does not handle "changed and unreferenced" case.

How should I store created objects in a dictionary so they are:

  • Could be garbage collected
  • Are not garbage collected when not referenced but changed?

Expanding on CodesInChaos' answer, I think you're on the right track using weak references in your original Dictionary and I think it makes sense to use a second data structure - probably a HashSet would work well here - that just holds references to objects which have been changed.

Remember, storing a reference to an object is cheap. I'd think you'd have to be on the order of millions or billions of references before it starts becoming a concern.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM