Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You could remove the "invalid" <code>WeakReference</code> inside <code>TryGetValue</code>:</p> <p><strong>[Edit]</strong> My mistake, these solutions actually do nothing more than what you suggested, since <code>Put</code> method will swap the old object with the new one anyway. Just ignore it.</p> <pre><code>public bool TryGetValue(TKey key, out TValue value) { WeakReference weakRef; if (!this.items.TryGetValue(key, out weakRef)) { value = null; return false; } else { value = (TValue)weakRef.Target; if (value == null) this.items.Remove(key); return (value != null); } } </code></pre> <p>Or, you can immediatelly create a new instance inside your dictionary, whenever it is needed:</p> <pre><code>public TValue GetOrCreate(TKey key, Func&lt;Tkey, TValue&gt; ctor) { WeakReference weakRef; if (!this.items.TryGetValue(key, out weakRef) { Tvalue result = ctor(key); this.Put(key, result); return result; } value = (TValue)weakRef.Target; if (value == null) { Tvalue result = ctor(key); this.Put(key, result); return result; } return value; } </code></pre> <p>You would then use it like this:</p> <pre><code>static Foo CreateFoo(int id) { return cache.GetOrCreate(id, id =&gt; new Foo(id)); } </code></pre> <p><strong>[Edit]</strong> </p> <p>According to windbg, <code>WeakReference</code> instance alone occupies 16 bytes. For 100,000 collected objects, this would not be such a serious burden, so you could easily let them live.</p> <p>If this is a server app and you believe you could benefit from collecting, I would consider going for a background thread, but also implementing a simple algorithm to <strong>increase waiting time</strong> whenever you collect a relatively small number of objects.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload