/// <summary> /// Promote a GC object for LRU /// </summary> /// <param name="handle">list handle returned by add</param> /// <param name="value">value to replace</param> /// <returns>this</returns> public LruList <T> Promote(LruHandle handle, T value) { long counter = Interlocked.Increment(ref _counter); _masterList.Update(handle.Index, x => new ItemDetail(value, counter)); _gen1.Enqueue(new ItemReference(handle, counter)); return(this); }
/// <summary> /// Add value to GC list /// </summary> /// <param name="value">value (must be not null)</param> /// <returns>GC handle</returns> public LruHandle Add(T value) { long counter = Interlocked.Increment(ref _counter); Prune(); int index = _masterList.Add(new ItemDetail(value, counter)); var lruHandle = new LruHandle(index); _gen1.Enqueue(new ItemReference(lruHandle, counter)); return(lruHandle); }
/// <summary> /// Set cache item. If value already exist, remove it and add the new one /// </summary> /// <param name="key">key</param> /// <param name="value">value</param> /// <returns>this</returns> public LruDictionary <TKey, TValue> Set(TKey key, TValue value) { lock (_lock) { ValueItem valueItem; if (_dict.TryGetValue(key, out valueItem)) { _lruList.Promote(valueItem.Handle, new KeyValuePair <TKey, TValue>(key, value)); return(this); } LruHandle handle = _lruList.Add(new KeyValuePair <TKey, TValue>(key, value)); _dict[key] = new ValueItem(value, handle); //_dict[key] = new ValueItem(value, new LruHandle(0)); return(this); } }
/// <summary> /// Get or create new item /// </summary> /// <param name="key">key</param> /// <param name="create">function to create</param> /// <returns>retrieved or created value</returns> public TValue GetOrCreate(TKey key, Func <TValue> create) { lock (_lock) { ValueItem valueItem; if (_dict.TryGetValue(key, out valueItem)) { _lruList.Promote(valueItem.Handle); return(valueItem.Value); } TValue value = create(); LruHandle handle = _lruList.Add(new KeyValuePair <TKey, TValue>(key, value)); _dict[key] = new ValueItem(value, handle); //_dict[key] = new ValueItem(value, new LruHandle(0)); return(value); } }
public ItemReference(LruHandle handle, long counter) { Handle = handle; Counter = counter; }
/// <summary> /// Remove item /// </summary> /// <param name="handle">handle of LRU</param> /// <returns>this</returns> public LruList <T> Remove(LruHandle handle) { _masterList.Remove(handle.Index); return(this); }
public ValueItem(TValue value, LruHandle handle) { Value = value; Handle = handle; }