简体   繁体   English

弱引用和非弱引用的字典

[英]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. 我有一个自定义类型MyClass和一个工厂类Factory ,该工厂类可根据要求创建MyClass类型的对象。

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. Factory将创建的对象存储在字典中,因为创建对象的成本很高,并且有时会要求多次创建同一对象。 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. 对象可能会并且可能不会在未知时间范围内存储在 Factory 外部的某个位置 Objects might be changed after creation. 创建后可能会更改对象。 There are times when Factory stores reference to an object and the object is not stored anywhere else. 有时Factory存储对对象的引用,而该对象不会存储在其他任何地方。

Now I want let garbage collector to do its job. 现在,我要让垃圾收集器完成其工作。 I want objects not stored anywhere outside Factory and not changed to be collected. 我希望不将对象存储在Factory之外的任何地方并且不进行更改以进行收集。

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. 我的第一个想法是对Factory中字典中的值使用弱引用,但似乎这种方法无法处理“更改和未引用”的情况。

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. 扩展CodesInChaos的答案,我认为您使用原始Dictionary弱引用在正确的轨道上,并且我认为使用第二个数据结构(可能在此处适用于HashSet是有意义的,该结构仅保存对对象的引用已经改变了。

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. 我认为,在您开始关注之前,您必须拥有数百万或数十亿个参考。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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