实作LRU快取

public class LRU<T> : ICache<T>
        {
            readonly List<T> _items;
            readonly int _capacity;
            public Action<T> AddCallback { get; set; }
            public Action<T> RemoveCallback { get; set; }
            public LRU(int capacity)
            {
                _capacity = capacity;
                _items = new List<T>();
            }
            public bool TryGet(Func<T, bool> filter, out T value)
            {
                lock (this)
                {
                    var i = 0;
                    while (i < _items.Count)
                    {
                        if (filter(_items[i]))
                        {
                            value = _items[i];
                            _items.RemoveAt(i);
                            _items.Insert(0, value);
                            return true;
                        }
                        i++;
                    }
                }
                value = default(T);
                return false;
            }
            public void Add(T value)
            {
                lock (this)
                {
                    _items.Insert(0, value);
                    AddCallback?.Invoke(value);
                    while (_items.Count > _capacity)
                    {
                        var last = _items.Count - 1;
                        var drop = _items[last];
                        _items.RemoveAt(last);
                        RemoveCallback?.Invoke(drop);
                    }
                }
            }
            public void Remove(Func<T, bool> filter)
            {
                lock (this)
                {
                    var i = 0;
                    while (i < _items.Count)
                    {
                        if (filter(_items[i]))
                        {
                            var drop = _items[i];
                            _items.RemoveAt(i);
                            RemoveCallback?.Invoke(drop);
                            continue;
                        }
                        i++;
                    }
                }
            }
            public T[] Dump()
            {
                lock (this)
                {
                    return _items.ToArray();
                }
            }
        }

 


上一篇