/// <summary> /// This handles creating the entry on first reference and removing the entry (and releasing on the value) /// for the scope on last dereference. /// </summary> public ScopedReferenceEntry CreateOrUpdateItem(ScopedReferenceEntry oldItem, bool hasOldItem, out bool remove) { TValue value; if (m_dereference) { Contract.Assert(hasOldItem, "Extraneous dereference detected. Ensure that scope is only disposed once"); // Check if dereferencing the last reference. If so, remove the item. remove = oldItem.ReferenceCount == 1; if (remove) { m_map.ReleaseValue(Key, oldItem.Value); return(default(ScopedReferenceEntry)); } value = oldItem.Value; return(new ScopedReferenceEntry(Key, value, oldItem.ReferenceCount - 1)); } else { remove = false; value = hasOldItem ? oldItem.Value : m_map.CreateValue(Key); return(new ScopedReferenceEntry(Key, value, oldItem.ReferenceCount + 1)); } }